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


当前回答

你可以试试

textview.setPaintFlags(textview.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);

其他回答

只需使用字符串资源文件中的属性,例如。

<string name="example"><u>Example</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>")

如果您使用的是字符串资源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);
HtmlCompat.fromHtml(
                    String.format(context.getString(R.string.set_target_with_underline)),
                    HtmlCompat.FROM_HTML_MODE_LEGACY)
<string name="set_target_with_underline">&lt;u>Set Target&lt;u> </string>

注意xml文件中的Escape符号

单线解决方案

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

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