【发布时间】:2011-06-08 03:01:39
【问题描述】:
我想让 TextView 完全加下划线,但我不能使用文本资源和 <u> 标签,因为它是动态文本。
到目前为止,我知道这样做的唯一方法是在运行时。这真的是唯一的方法吗?有没有办法在 XML 文件中做到这一点?
【问题讨论】:
我想让 TextView 完全加下划线,但我不能使用文本资源和 <u> 标签,因为它是动态文本。
到目前为止,我知道这样做的唯一方法是在运行时。这真的是唯一的方法吗?有没有办法在 XML 文件中做到这一点?
【问题讨论】:
如果您愿意,也可以通过 /res/values/string.xml 文件执行此操作:例如,在 /res/values/string.xml 中,您可以添加如下条目:
<string name="createAccount"><u>Create Account</u></string>
然后在您的活动的 onCreate(Bundle savedInstanceState) 方法中,您将添加以下代码以使“创建帐户”> 在您为 xml 文件中定义的 createAccountText TextView 设置的 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);
【讨论】:
textView.setText(getResources().getString(R.string.string_id)); 文本没有下划线。
SpannableString content = new SpannableString(name);
content.setSpan(new UnderlineSpan(), 0, name.length(), 0);
geometrical_textview.setText(content, TextView.BufferType.SPANNABLE);
【讨论】:
peter3 之前写过扩展 TextView 类并重写 setText 方法。
此解决方案不起作用,因为 setText 方法被标记为 FINAL。
http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)
不确定代码是否可以进行一些修改。
【讨论】:
最简单的解决方案可能是创建一个从 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
【讨论】:
你可以在Html.fromHtml(String source)上加下划线
例子:
textView.setText(Html.fromHtml("this is <u>underlined</u> text"));
【讨论】:
<u> 和</u> 标签的左括号没有被转义。有关正确示例,请参阅stackoverflow.com/a/9955051/425183