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


当前回答

单线解决方案

myTextView.setText(Html.fromHtml(“<p><u>我是下划线文本</u></p>”));

这有点晚了,但可能对某人有用。

其他回答

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

<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>

结果:

如果要在XML中实现这一点,请在resource中声明字符串,并将该资源值放入HTML的下划线标记(<u></u>)中。在TextView中,添加

android:text="@string/your_text_reference"

在字符串资源值中,

<string name="your_text_reference"><u>Underline me</u></string>

如果您想以编程方式实现这一点,请使用Kotlin

textView.paintFlags = textView.paintFlags or Paint.UNDERLINE_TEXT_FLAG

or,

textView.text = Html.fromHtml("<p><u>Underline me</u></p>")

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

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

如果您使用的是字符串资源xml文件,该文件支持HTML标记,如<b></b>、<i></i>和<u></u>,则可以实现这一点。

<resources>
    <string name="your_string_here"><![CDATA[This is an <u>underline</u>.]]></string>
</resources>

如果您想在代码中添加下划线,请使用:

TextView textView = (TextView) view.findViewById(R.id.textview);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textView.setText(content);

在Kotlin中可以使用扩展函数。这只能从代码中使用,而不能从xml中使用。

fun TextView.underline() {
    paintFlags = paintFlags or Paint.UNDERLINE_TEXT_FLAG
}

用法:

 tv_change_number.underline()
 tv_resend_otp.underline()