標籤:android style ar os 使用 sp for 檔案 on
在項目中代碼中儘可能少出現中文(注釋除外),對此,就需要將字串設定到string.xml中
通常用法
EXAMPLE 1:
string.xml中配置:<string name="hello">Hello!</string>
layout xml中使用方式為:<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
code 中使用方式為:String string = getString(R.string.hello); / String string = getResources().getString(R.string.hello);
當然string.xml中也允許設定字串數組
EXAMPLE 2:
string.xml中配置:<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
code 中使用方式為:Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);
需要注意的是,在設定檔中會使用到特殊字元,eg:英文狀態下的單引號“\‘” ,分行符號“\n”, 百分比符號“\%”, “\@”符號
EXAMPLE 3:
string.xml中配置:正確:<string name="good_example">"This‘ll work"</string> --在雙引號中僅僅是作為字串輸出
<string name="good_example_2">This\‘ll also work</string> --不帶雙引號,則需要考慮逸出字元
<string name="good_example_3" formatted="false">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.xml中也支援萬用字元方式
EXAMPLE 4:
string.xml中配置:<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
%1、%2代表參數的順序,$s表示輸出字串,$d表示輸出十進位整數, $f表示輸出十進位浮點數
code 中使用方式為:Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
最後是帶HTML樣式的字串
EXAMPLE 5:
string.xml中配置:<string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string>
這裡需要注意的是逸出字元的使用,eg:< 或 &,可參考EXAMPLE 3
code 中使用方式為:Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
這裡需要注意參數1:username,如果username中包含了特殊字元 < 或 & 時,需要將其中的特殊字元轉義
String escapedUsername = TextUtil.htmlEncode(username);
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount);
CharSequence styledText = Html.fromHtml(text);
根據官府文檔的介紹就到這裡,其中還缺少一個關於特殊字元Quantity String的用法,沒看明白官方文檔的說明也比較少用到,就忽略吧
Android R.string