• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

在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

 

posted @ 2013-08-29 18:47  Class Xman  阅读(524)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3