使用注解设置样式
您可以通过使用 strings.xml 资源文件中的 Annotation
类和 <annotation>
标记,应用复杂样式或自定义样式。借助注解标记,您可以通过在 XML 文件中定义自定义键值对来标记自定义样式的部分字符串,框架随后会将该 XML 文件转换成 Annotation
span。然后,您便可检索这些注解,并使用键和值来应用样式。
// values/strings.xml <string name="title">Best practices for <annotation font="title_emphasis">text</annotation> on Android</string> // values-es/strings.xml <string name="title"><annotation font="title_emphasis">Texto</annotation> en Android: mejores prácticas</string>
加载字符串资源并找到包含 font 键的注解。然后,创建一个自定义 span,并用其替换现有 span。
SpannedString titleText = (SpannedString) getText(R.string.title_about); Annotation[] annotations = titleText.getSpans(0, titleText.length(), Annotation.class); SpannableString spannableString = new SpannableString(titleText); for (Annotation annotation: annotations) { if (annotation.getKey().equals("font")) { String fontName = annotation.getValue(); if (fontName.equals("title_emphasis")) { Typeface typeface = ResourcesCompat.getFont(this, R.font.roboto_mono); spannableString.setSpan(new CustomTypefaceSpan(typeface), titleText.getSpanStart(annotation), titleText.getSpanEnd(annotation), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } styledText.text = spannableString;