安卓控件对带有Html标签的字符串使用方法:
1.直接在string的XML文件中定义,并在layout中直接引用。
String中:
<string name="welcome"><b>Hello World!</b></string>
<string name="welcome1"><b>Hello World!</b></string>
控件中引用:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome1" />
效果:
从上面发现,这种效果不能使用转义的Html标签。
2.第二种我们可以在代码中直接使用空间的setText()函数设定。
看代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textView);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView.setText("<b>Hello World!</b>");
textView1.setText("<b>Hello World!</b>");
}
看效果:
从图中可以看到setText()函数直接接收带有HTML标签的String对象是不能被解释的。只要将代码稍微改一下就可以:
textView.setText(Html.fromHtml("<b>Hello World!</b>"));
textView1.setText(Html.fromHtml("<b>Hello World!</b>"));
效果:
可以发现,setText()函数只支持带有HTML标签的CharSequence类型字符串。还可以发现,Html.fromHtml()函数不能解释转义的Html标签。所以我们可以理解为,android在扩展控件时,对string资源扩展就使用的是Html.fromHtml()函数。
3.还有理解两个函数getString()。
<string name="welcome"><b>Hello World!</b></string>
<string name="welcome1"><b>Hello World!</b></string>
<string name="welcome2">Hello World!</string>
代码中:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = getString(R.string.welcome);
String string1 = getString(R.string.welcome1);
String string2 = getString(R.string.welcome2);
Log.d("TestResources", string);
Log.d("TestResources", string1);
Log.d("TestResources", string2);
}
看看LogCat:
我们发现,getString只能正确扩展转义后Html标签。因此要在代码中利用带有Html标签的字符串资源就必须将字符串的Html标签转义。如下所示:
<string name="welcome1"><b>Hello World!</b></string>
代码中:
TextView textView = (TextView) findViewById(R.id.textView);
String string = getString(R.string.welcome);
textView.setText(Html.fromHtml(string));
现在来总结一下,Layout布局文件直接引用带有Html标签的字符串必须定义为完整的不转义标签的字符串。Html.fromHtml()函数也支持完整的不转义的Html标签。只有代码中的函数访问String资源时需要对Html进行转义。