如何在Android布局xml文件中定义带下划线的文本?


当前回答

查看带下划线的可单击按钮样式:

<TextView
    android:id="@+id/btn_some_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_add_contact"
    android:textAllCaps="false"
    android:textColor="#57a0d4"
    style="@style/Widget.AppCompat.Button.Borderless.Colored" />

字符串.xml:

<string name="btn_add_contact"><u>Add new contact</u></string>

结果:

其他回答

最简单的方法

TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");

还支持TextView子项,如EditText、Button、Checkbox

public void setUnderLineText(TextView tv, String textToUnderLine) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToUnderLine, 0);

        UnderlineSpan underlineSpan = new UnderlineSpan();
        SpannableString wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToUnderLine, ofs);
            if (ofe == -1)
                break;
            else {
                wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }

如果你愿意

-可单击下划线文本?

-给TextView的多个部分加下划线?

然后检查此答案

罗曼·盖伊(Romain Guy)用GitHub上的可用源代码描述了最新的画下划线文本的方法。此示例应用程序公开了两种可能的实现:

需要API级别19的基于路径的实现需要API级别1的基于区域的实现

一种更干净的方式,而不是textView.setPaintFlags(textView.getPaintFlags()|Paint.UNDERLINE_EXT_FLAG);方法是使用textView.getPaint().setUnderlineText(true);

如果您需要稍后关闭该视图的下划线,例如在RecyclerView中的重用视图中,textView.getPaint().setUnderlineText(false);

要在Kotlin做到这一点:

你的TextView.praint?。isUnderlineText=真

     <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:backgroundTint="@android:color/transparent"
                    android:hint="@string/search_url"
                    android:textColor="@color/coffee_color"
                    android:textColorHint="@color/coffee_color"
                    />