【发布时间】:2012-01-23 09:35:20
【问题描述】:
在 android 中是否有可能在 Java 代码中为 TextView 提供一些带有 setText(text) 函数的文本,这些文本带有基本标签,如和 以使标记的单词加下划线?
【问题讨论】:
-
This will help you, 这是您可以
underlinetextview 文本和italic的示例。
在 android 中是否有可能在 Java 代码中为 TextView 提供一些带有 setText(text) 函数的文本,这些文本带有基本标签,如和 以使标记的单词加下划线?
【问题讨论】:
underline textview 文本和italic 的示例。
是的,你可以,使用 Html.fromhtml() 方法:
textView.setText(Html.fromHtml("this is <u>underlined</u> text"));
【讨论】:
textView.setText(Html.fromHtml(getResources().getString(R.string.have_activation_code)));<string name="have_activation_code"><u>I have activation code</u></string>
Html.fromHtml 现已弃用
定义一个字符串为:
<resources>
<string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>
【讨论】:
Html.fromHtml() 不支持某些标签。看看这个stackoverflow.com/a/3150456/1987045
您可以使用 SpannableString 类中的 UnderlineSpan:
SpannableString content = new SpannableString(<your text>);
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
那就用textView.setText(content);
【讨论】:
tobeunderlined= <u>some text here which is to be underlined</u>
textView.setText(Html.fromHtml("some string"+tobeunderlined+"somestring"));
【讨论】:
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 的多个部分下划线?
【讨论】: