为了代码规范化,这几天尝试了string.xml的使用:
1、通配符的使用:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
在上面代码中,这个格式化的字符串有2个参数
%n$ms:代表输出的是字符串,n代表是第几个参数,设置m的值可以在输出之前放置空格
%n$md:代表输出的是整数,n代表是第几个参数,设置m的值可以在输出之前放置空格,也可以设为0m,在输出之前放置m个0
%n$mf:代表输出的是浮点数,n代表是第几个参数,设置m的值可以控制小数位数,如m=2.2时,输出格式为00.00
在java代码中照下面的方法来根据参数来格式化字符串:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
2、然后是数组的用法:
<string-array name="type_list">
<item>全部</item>
<item>充值记录</item>
<item>网银消费</item>
<item>充值消费</item>
</string-array>
在java代码中照下面的方法来格式化数组:
getResources().getStringArray(R.array.type_list);
或者
this.getStringArray(R.array.type_list);
3、然后是image 图片资源的使用方法:
<string-array name="feed_icons">
<item>@drawable/latest</item>
<item>@drawable/video</item>
<item>@drawable/world</item>
<item>@drawable/sports</item>
<item>@drawable/arts</item>
<item>@drawable/dining</item>
</string-array>
在java代码中使用方法:
Map<String, Object> map;
TypedArray ta = getResources().obtainTypedArray(R.array.feed_icons);
String[] titleArr = getResources().getStringArray(R.array.feed_names);
for(int i=0; i<titleArr.length; i++)
{
map = new HashMap<String, Object>();
map.put("icon", ta.getResourceId(i, 0));
map.put("title", titleArr[i]);
list.add(map);
}
注意:TypedArray是关键,代码中去图片时候要这么用int id = ta.getResourceId(index, 0);
4、最后是字符串,这个最简单了。
<span style="white-space:pre"> </span><string name="old_pass">请输入旧密码</string>
<string name="new_pass">请输入新密码</string>
<string name="confirm_pass">请确认密码</string>
取值很简单:
getResources().getString(R.string.name)
当然还可以直接在xml文件中使用,这里就不在赘述了!
另外,Html.fromHtml(text)支持的html标签却不只这些,具体有那些android平台并没有详细列举.在 HTML Tags Supported By TextView 有详细列举.但是额外的标签不能直接定义在xml中.貌似会被过滤掉.所以使用额外的标签时,必须用<![CDATA[ xx ]]>包围住.当然这样的字符串就不能直接在xml中调用了.只能通过代码使用.
<string name="welcome_info_2"> <![CDATA[欢迎你,<font color="#c5663e">%s</font>]]></string>
本文介绍了 Android 开发中 string.xml 的多种实用技巧,包括通配符格式化字符串、数组使用、图片资源引用及基本字符串定义等。
39

被折叠的 条评论
为什么被折叠?



