我遵循了Styling internationalized text in Android中的教程,并使用了代码:
SpannedString titleText = (SpannedString) getText(R.string.title);
Annotation[] annotations = titleText.getSpans(0, titleText.length(), Annotation.class);
SpannableString spannableString1 = new SpannableString(titleText);
for (Annotation annotation : annotations) {
if (annotation.getKey().equals("id")) {
final String fontName = annotation.getValue();
spannableString1.setSpan(new StyleSpan(Typeface.BOLD),
titleText.getSpanStart(annotation),
titleText.getSpanEnd(annotation),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString1.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this, fontName + "", Toast.LENGTH_SHORT).show();
}
}, titleText.getSpanStart(annotation), titleText.getSpanEnd(annotation), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(spannableString1);我用string.xml中的string <string name="title"><i>Best practices for</i> <annotation id="1">text1</annotation> on Android <annotation id="2">text2</annotation></string>对此进行了测试,它运行得非常好。但是我想用代码将字符串从string.xml移动到MainActivity.class
String title="<i>Best practices for</i> <annotation id=\"1\">text1</annotation> on Android <annotation id=\"2\">text2</annotation>";
SpannedString titleText = new SpannedString(title);//
Annotation[] annotations = titleText.getSpans(0, titleText.length(), Annotation.class);
...但它不起作用。它显示了我的TextView中html的所有标签。如何将文本从string.xml更改为MainActivity.java并获得相同的结果?
发布于 2019-05-16 15:29:28
使用HtmlCompat.fromHtml():
SpannedString titleText = new SpannedString(HtmlCompat.fromHtml(title, HtmlCompat.FROM_HTML_MODE_LEGACY));https://stackoverflow.com/questions/56162437
复制相似问题