在strings.xml中定义html标签

在项目的开发过程中,需要用到把html内容放到strings.xml文件中,然后再读取到TextView中.原本以为像普通文本一样直接SetText就行了,结果行不通,大大超出我的预料.经过网上搜索,找到一些方法,自己经过整理,在此记录下来,另附上自己的测试工程.

先贴上strings.xml文件中重点内容:

<string name="msg1">
	    <b>Hello world!</b><br/>
	    <a href="http://blog.csdn.net/Banket004">link</a>
	    </string>
	<string name="msg2">
	    <![CDATA[
	    <b>Hello world!</b><br/>
	    <a href="http://blog.csdn.net/Banket004">link</a>
	    ]]>
	    </string>


方法一:普通html string 加上Context的getText

这方法能处理html中和xml共有的标签,但无法正确解析像"<br />"这种xml所没有的标签.容易造成某些标签被忽略,实际上是用xml标签实现html标签的效果,且只能用Context的getText获取带有格式的html文本,如果用Context的getString获取,html文本的格式标签会被自动过滤掉.此方法不需要用到Html类.部分代码如下:

TextView view1 = (TextView)findViewById(R.id.textView1);
		TextView view2 = (TextView)findViewById(R.id.textView2);
		TextView view3 = (TextView)findViewById(R.id.textView3);
		TextView view4 = (TextView)findViewById(R.id.textView4);
		TextView view5 = (TextView)findViewById(R.id.textView5);
		TextView view6 = (TextView)findViewById(R.id.textView6);
		TextView view7 = (TextView)findViewById(R.id.textView7);
		TextView view8 = (TextView)findViewById(R.id.textView8);
		
		
		view1.setText(getString(R.string.msg1));
		view2.setText(getText(R.string.msg1));
		view3.setText(Html.fromHtml(getString(R.string.msg1)));
		view4.setText(Html.fromHtml(getText(R.string.msg1).toString()));


方法二:特殊处理的html string 加上Context的getString(或者getText).

这个方法需要对strings.xml文件中对应的string进行处理,在html内容最前面加上"<![CDATA[",在html内容末尾加上"]]",在使用的时候直接通过Context的getString(或者getText)方法获取,然后使用Html的fromHtml方法得到html内容对应的Spanned,最后调用TextView的SetText即可.部分代码如下:

view5.setText(getString(R.string.msg2));
		view6.setText(getText(R.string.msg2));
		view7.setText(Html.fromHtml(getString(R.string.msg2)));
		view8.setText(Html.fromHtml(getText(R.string.msg2).toString()));


对应测试工程下载地址:http://download.csdn.net/detail/banket004/6033697

效果图如下:



参考:http://stackoverflow.com/questions/3235131/set-textview-text-from-html-formatted-string-resource-in-xml/18199543#18199543

原文地址:https://www.cnblogs.com/james1207/p/3289826.html