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


当前回答

你可以试试

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

其他回答

转到strings.xml资源文件必要时,在资源文件中添加带有HTML下划线标记的字符串。

strings.xml HTML下划线示例

按如下方式调用Java代码中的字符串资源ID:

sampleTextView.setText(R.string.sample_string);

输出应带有下划线的单词“Stacksoverflow”。

此外,以下代码不会打印下划线:

String sampleString = getString(R.string.sample_string);
sampleTextView.setText(sampleString);

相反,使用以下代码保留RTF格式:

CharSequence sampleString = getText(R.string.sample_string);
sampleTextView.setText(sampleString);

“您可以使用getString(int)或getText(int)来检索字符串。getText(int)保留应用于字符串的任何富文本样式。”Android文档。

请参阅文档:https://developer.android.com/guide/topics/resources/string-resource.html

我希望这有帮助。

我使用这个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>

我简化了塞缪尔的回答:

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

如果要在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);