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


当前回答

我使用这个xml可绘制文件来创建底部边框,并将可绘制文件作为背景应用到文本视图中

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <item android:top="-5dp" android:right="-5dp" android:left="-5dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                    android:width="1.5dp"
                    android:color="@color/pure_white" />
        </shape>
    </item>
</layer-list>

其他回答

单线解决方案

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

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

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

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

<string name="example"><u>Example</u></string>

非常紧凑的科特林版本:

tvTitle.apply { 
    text = "foobar"
    paint?.isUnderlineText = true
}

Strings.xml文件内容:

<resource>
     <string name="my_text">This is an <u>underline</u>.</string> 
</resources> 

布局xml文件应使用具有textview以下财产的上述字符串资源,如下所示:

<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="@string/my_text"

    android:selectAllOnFocus="false"
    android:linksClickable="false"
    android:autoLink="all"
    />