Android:在TextView中静态地下划线动态文本

6
我想让一个TextView完全下划线,但是我不能使用文本资源和标签,因为它是动态文本。目前我知道的唯一方法是在运行时完成。这真的是唯一的方法吗?有没有办法可以在XML文件中完成?相关问题请参考:Can I underline text in an android layout?
5个回答

18

最简单的解决方案可能是创建一个自定义的UnderLineTextView组件来继承TextView,重写setText()方法并将整个文本设置为带下划线的,类似于这样(下划线代码来自您上面提到的链接):

@Override
public void setText(CharSequence text, BufferType type) {
    // code to check text for null omitted
    SpannableString content = new SpannableString(text);
    content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
    super.setText(content, BufferType.SPANNABLE);

}

接下来只需要在布局中使用你的新组件,然后像往常一样设置文本即可,其余的部分会自动处理。

更多有关自定义组件的信息请参考: http://developer.android.com/guide/topics/ui/custom-components.html


14

您可以使用下面的代码在文本上方加下划线:Html.fromHtml(String source)

示例:

textView.setText(Html.fromHtml("this is <u>underlined</u> text"));

这不会起作用,因为<u></u>标签的开括号没有被转义。请参见https://dev59.com/F3E95IYBdhLWcg3wPrgI#9955051以获取正确的示例。 - Ognyan

1

如果您喜欢,也可以通过/res/values/string.xml文件来完成此操作。例如,在/res/values/string.xml中,您可以添加一个条目,如下所示:

<string name="createAccount"><u>Create Account</u></string>

在您的活动的onCreate(Bundle savedInstanceState)方法中,您可以添加以下代码,使“创建帐户”在您为createAccountText TextView在/xml文件中定义的UI中以下划线形式出现,该文件位于您的活动的/res/layout/目录下:
TextView createAccountText = (TextView) findViewById(R.id.createAccountText);
Resources res = getResources();
CharSequence styledText = res.getText(R.string.createAccount);
createAccountText.setText(styledText, TextView.BufferType.SPANNABLE);

getResources().getText() 解决了我的问题,不知道为什么使用 textView.setText(getResources().getString(R.string.string_id)); 时文本没有被下划线。 - Luca Nicoletti

0
 SpannableString content = new SpannableString(name);
 content.setSpan(new UnderlineSpan(), 0, name.length(), 0);
 geometrical_textview.setText(content, TextView.BufferType.SPANNABLE);

0

Peter3覆盖的方法不是public final void setText(CharSequence text),而是public void setText(CharSequence text, TextView.BufferType type)。Peter3所描述的方法并非final。(略晚了一些添加评论,但我也得看两次,所以认为值得一提)。 - Stanley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接