1 轻量级样式标签
Android支持(加粗)、(倾斜)、(下划线)等轻量级html标签,可直接在资源文件strings.xml中使用
strings.xml
Hello world!
Hello world!
Hello world!
Hello world!
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world01"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world02"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world03"/>
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
实现效果如下:
2 使用转义html标签
能够直接使用的标签比较有限,若要实现其他效果,如改变字体颜色或者大小等,可使用转义html标签,或者接下来所述的CDDATA方法;
简单了解下转义标签,首先,定义转义字符串的原因有两个:
第一个原因是像“<”和“>”这类符号已经用来表示HTML标签,因此就不能直接当作文本中的符号来使用。
第二个原因是,有些字符在ASCII字符集中没有定义,因此需要使用转义字符串来表示。
例如:< 转义为 < > 转义为 > 空格 转义为 等等。。。其他可百度"html转义字符"
继上例strings.xml 注:将左尖括号替换为转义符<
<b>Hello world!</b>
MainActivity.java 注意设置字符串方法
TextView tvBold = (TextView) findViewById(R.id.tv01);
tvBold.setText(Html.fromHtml(getString(R.string.hello_world01)));
3 使用CDATA方法
据称该方法是比较推荐的,具体操作如下,许多html标签都可以使用,
~
,,
,还有设置字体大小如,等等。。。具体可以谷歌下哦O(∩_∩)O
strings.xml
<![CDATA[ Hello
world!
]]>
MainActivity.java
TextView tvTest= (TextView) findViewById(R.id.tv_test);
tvTest.setText(Html.fromHtml(getString(R.string.textTest)));
实现效果:
4 格式化替换
对于静态字符串中,某些一个或者多个地方可能是需要动态获取的,此时可使用此方法,免去了添加多个TextView的麻烦,并且可与上述改变文字样式的方法相结合使用,关于这点,只需先作格式化替换,再用上述Html.fromHtml(Str…)方法改变文字样式,即可实现想要的效果,详情可查看我的参考文章。
strings.xml
Tom%1
s
就
要
s就要%2
s就要d岁了
其中,s表示字符串类型,d表示数字类型…其他还有浮点型等并且可以设置显示格式,比如保留几位小数等。。。
activity_main.xml
<TextView
android:id="@+id/tv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
MainActivity.java
TextView tvTest= (TextView) findViewById(R.id.tv_test);
tvTest.setText(String.format(getString(R.string.textTest), “明年”,12));