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


当前回答

如果要在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使用“WRAP_CONTENT”,因为没有多余的空间来绘制线条。您可以为TextView设置固定高度,或者使用android:ppaddingVertical和WRAP_CONTENT。

单线解决方案

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

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

如果要在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可绘制文件来创建底部边框,并将可绘制文件作为背景应用到文本视图中

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

对于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);