6

我想让 TextView 完全加下划线,但我不能使用文本资源和<u>标签,因为它是动态文本。

相关:我可以在 android 布局中为文本加下划线吗?

到目前为止,我知道这样做的唯一方法是在运行时。这真的是唯一的方法吗?有没有办法在 XML 文件中做到这一点?

4

5 回答 5

18

最简单的解决方案可能是创建一个从 TextView 派生的自定义 UnderLineTextView 组件,覆盖 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

于 2011-01-12T21:31:50.293 回答
14

您可以在Html.fromHtml(String source)上为文本添加下划线

例子:

textView.setText(Html.fromHtml("this is <u>underlined</u> text"));
于 2011-01-12T21:25:31.277 回答
1

如果您愿意,也可以通过/res/values/string.xml文件执行此操作:例如,/res/values/string.xml您可以在其中添加如下条目:

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

然后在您的活动的 onCreate(Bundle savedInstanceState) 方法中,您将添加以下代码以使“创建帐户”> 在您为您在 xml 文件中/res/layout/为您的 xml 文件中定义的 createAccountText TextView 设置的 UI 中显示为下划线活动:

TextView createAccountText = (TextView) findViewById(R.id.createAccountText);
Resources res = getResources();
CharSequence styledText = res.getText(R.string.createAccount);
createAccountText.setText(styledText, TextView.BufferType.SPANNABLE);
于 2011-01-26T16:45:48.247 回答
0

peter3 之前写过扩展 TextView 类并覆盖 setText 方法。

此解决方案将不起作用,因为 setText 方法被标记为 FINAL。

http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)

不确定代码是否可以进行一些修改。

于 2015-03-03T22:45:55.747 回答
0
 SpannableString content = new SpannableString(name);
 content.setSpan(new UnderlineSpan(), 0, name.length(), 0);
 geometrical_textview.setText(content, TextView.BufferType.SPANNABLE);
于 2016-04-22T00:44:31.193 回答