高级字符串用法

来源:互联网 发布:js中class选择器 编辑:程序博客网 时间:2024/06/13 21:49

这是strings.xml里面的代码,如下

<string name=”personal_welcome_message”>Welcome %s!</string><plurals name=”inbox_message_count”><item quantity=”zero”>Your inbox is completely empty!</item><item quantity=”one”>You one message in your inbox!</item><item quantity=”two”>You two messages waiting to be read!</item><item quantity=”few”>You have %d messages waiting!</item><item quantity=”many”>%1$d messages in your inbox! %2$s, youshould really login here more often!</item><item quantity=”other”>%1$d messages in your inbox! %2$s, youshould really login here more often!</item></plurals><string-array name=”default_categories”><item>Work</item><item>Personal</item><item>Private</item><item>Spam</item><item>Trash</item><item>Draft</item></string-array>

格式化

Strings.xml可以写格式化字符串,此处%s可用String来填补

例子

    public void showWelcomeMessage(String name) {        ((TextView) findViewById(R.id.welcome_message_field)).        setText(getString(R.string.personal_welcome_message, name));}

复数

示例代码

public void showInboxCountMessage(int inboxCount, String name) {        Resources res = getResources();        String inboxCountMessage = res.                getQuantityString(R.plurals.inbox_message_count, inboxCount,                        name);        ((TextView) findViewById(R.id.inbox_count_field)).                setText(inboxCountMessage);}

这种方式主要用来处理不同数量时显示不同的字符串,getQuantityString的第二个参数就是数量,android里的数量有几种zero,one,two,few,many

可参考http://blog.csdn.net/ff313976/article/details/7439676

 

字符串数组

可以把一些相关的字符串放入一个字符串数组内,示例代码如下

public void displayCategories() {        ListView listView = (ListView) findViewById(R.id.category_list);        Resources res = getResources();        String[] categories = res.getStringArray(R.array.default_categories);        ArrayAdapter<String> categoriesadapter = new                ArrayAdapter<String>(this,                android.R.layout.simple_list_item_1, android.R.id.text1,                categories);        listView.setAdapter(categoriesadapter);}

参考文献

android pragramming push the limits

0 0
原创粉丝点击