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


当前回答

上面的“接受”答案不起作用(当您尝试使用textView.setText(Html.fromHtml(string.format(getString(…),…)))这样的字符串时)。

如文档中所述,您必须用<,例如,结果应如下所示:

<resource>
    <string name="your_string_here">This is an &lt;u&gt;underline&lt;/u&gt;.</string>
</resources>

然后在代码中,您可以使用以下选项设置文本:

TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(String.format(getString(R.string.my_string), ...)));

其他回答

单线解决方案

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

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

对于Button和TextView,这是最简单的方法:

按钮:

Button button = (Button) findViewById(R.id.btton1);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

文本视图:

TextView textView = (TextView) findViewById(R.id.textview1);
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

我简化了塞缪尔的回答:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--https://stackoverflow.com/a/40706098/4726718-->
    <item
        android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp">
        <shape>
            <stroke
                android:width="1.5dp"
                android:color="@color/colorAccent" />
        </shape>
    </item>
</layer-list>

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

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

结果:

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

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

用法:

 tv_change_number.underline()
 tv_resend_otp.underline()