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


当前回答

转到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文件,该文件支持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);

最简单的方法

TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");

还支持TextView子项,如EditText、Button、Checkbox

public void setUnderLineText(TextView tv, String textToUnderLine) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToUnderLine, 0);

        UnderlineSpan underlineSpan = new UnderlineSpan();
        SpannableString wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToUnderLine, ofs);
            if (ofe == -1)
                break;
            else {
                wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }

如果你愿意

-可单击下划线文本?

-给TextView的多个部分加下划线?

然后检查此答案

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

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

结果:

尝试此代码

XML格式

<resource>
 <string name="my_text"><![CDATA[This is an <u>underline</u>]]></string> 
</resources> 

在代码中

TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.my_text)));

祝你好运

单线解决方案

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

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