Android字符串资源

目录

 

1、string字符串

2、String array字符串数组

3、Quantity strings (plurals)复数字符串

4、字符串格式和风格

4.1、格式:

4.2、使用HTML标记设置样式

4.3、其它关于string resource的使用


1、string字符串

提供单个字符串的xml资源

文件位置:

res/values/filename.xml

这里的filename名称随意,没有固定要求,比如常用的strings,但是定义的字符串要放在<string></string>标签里面。

引用字符串:

在java中:R.string.string_name

在xml中:@string/string_name

在xml中的定义如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello!</string>
</resources>

在布局文件中引用:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

在java代码中使用资源字符串有两个方法getString(int)和getText(int),比如下面的getString:

String string = getString(R.string.hello);

2、String array字符串数组

文件位置:

res/values/filename.xml

filename的命名同样是没有限制的,比如strings

在xml中的定义如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

在java代码中引用定义好的字符串数组:

Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);

3、Quantity strings (plurals)复数字符串

同样也可以跟string定义到同一个strings文件下

<resources>
    <plurals name="numberOfSongsAvailable">
        <item quantity="one">Znaleziono %d piosenkę.</item>
        <item quantity="few">Znaleziono %d piosenki.</item>
        <item quantity="other">Znaleziono %d piosenek.</item>
    </plurals>
</resources>

在java中使用:

int count = getNumberOfSongsAvailable();
Resources res = getResources();
String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);

plurals复数通常用于英语环境,中文环境使用场景较少,因为中文句式不会因为某些数量的变化而改变句型,比如1个苹果是“1 apple”,2个苹果是“2 apples”,多个的时候apple会变成复数。而中文“1个苹果”和“2个苹果”句式是不会变的,只有数字会改变。

这里getQuantityString方法第二个参数是代表plurals,第三个参数是对应“%d”填充的内容,这里的d代表整数,如果是字符串的话就要用“%s”。

4、字符串格式和风格

4.1、格式:

例如:

<string name="welcome_messages">Hello, %s! You have %d new messages.</string>

在java代码中使用该字符串:

String text = getString(R.string.welcome_messages, username, mailCount);

4.2、使用HTML标记设置样式

在资源文件中定义字符串:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="welcome">Welcome to <b>Android</b>!</string>
</resources>

在java代码中使用该字符串:

TextView mChargingImageView = (ImageView) findViewById(R.id.iv_power_increment);
String text = getString(R.string.welcome_messages, username, mailCount);
Spanned styledText = Html.fromHtml(text, FROM_HTML_MODE_LEGACY);
mChargingCountDisplay.setText(styledText);

fromHtml方法在api24的时候引入,api低于24则无法使用该方法

4.3、其它关于string resource的使用

参考链接

猜你喜欢

转载自blog.csdn.net/yann02/article/details/94589937