android developers上说的,string resource 不仅能定义字符串,还支持字符串的styling和formatting。 android
通过如下方法来定义字符串资源
字符串
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="string_name" >text_string</string> </resources> name 属性为该string的id。可通过 Activity的getString(id)的方法在代码中获得字符串的值。
字符串数组
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="string_array_name"> <item >text_string</item> </string-array> </resources> 在代码里面可以这样获得字符串数组资源
Resources res = getResources(); String[] planets = res.getStringArray(R.array.planets_array); 字符串格式化 在字符串中出现单引号和双引号,不能直接写于xml中:
<string name="good_example">"This'll work"</string> <string name="good_example_2">This\'ll also work</string> <string name="bad_example">This doesn't work</string> <string name="bad_example_2">XML encodings don't work</string> 在资源中定义的字符串同样支持格式化.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string> Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount); 使用HTML标签
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="welcome">Welcome to <b>Android</b>!</string> </resources> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/welcome" /> 这样在TextView中”Android”会显示为粗体. 在代码中可以这样使用:
Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount); CharSequence styledText = Html.fromHtml(text); 在文档中说支持的html标签,只有:
<b> <i> <u> 但是,Html.fromHtml(text)支持的html标签却不只这些,具体有那些android平台并没有详细列举.在 HTML Tags Supported By TextView 有详细列举.但是额外的标签不能直接定义在xml中.貌似会被过滤掉.所以使用额外的标签时,必须用<![CDATA[ xx ]]>包围住.当然这样的字符串就不能直接在xml中调用了.只能通过代码使用.
|
|