實際開發的過程當中咱們有時候會遇到,一個TextView裏面會遇到會有一個一大串固定的文字,而裏面的數字或者個別字須要根據後臺的接口而展現的。這個時候咱們最簡單的方法就是在string.xml文件裏 使用 %s、%1$s、%d、%1$d,而在頁面展現的時候咱們只須要用實際展現的文字或者數據替換掉這些佔位符就能夠了。android
%1$s表示把第一個位置的佔位符替換成string類型ui
%1$d表示把第一個位置的佔位符替換成int類型spa
數字表示替換字符串中第幾個被替換的位置,若一個字符串要替換兩個int類型,在替換位置分別寫%1$d和%2$d..net
%s 、%d爲縮寫方式,只替換一個位置,能夠這麼寫。code
例1: %sxml
strings.xmlblog
<string name="strings1">My name is %s</string>
代碼中:接口
TextView tv_text = findViewById(R.id.tv_text); String text = getString(R.string.strings1, "Tom"); tv_text.setText(text); Log.i(TAG, "text: "+text);
Log:開發
I/StringsApiUseDemoActivity: text: My name is Tom字符串
例2:%d
<string name="strings1">My age is %d</string>
代碼中:
TextView tv_text = findViewById(R.id.tv_text); String text = getString(R.string.strings2, 20); tv_text.setText(text); Log.i(TAG, "text: "+text);
Log:
I/StringsApiUseDemoActivity: text: My age is 20
例3:%1$s
<string name="strings3">My name is %1$s, you name is %2$s, others name is %3$s</string>
代碼中:
TextView tv_text = findViewById(R.id.tv_text); String text = getString(R.string.strings3, "Tom", "Mike", "John"); tv_text.setText(text); Log.i(TAG, "text: "+text);
Log:
I/StringsApiUseDemoActivity: text: My name is Tom, you name is Mike, others name is John
例4:%1$d
<string name="strings4">My age is %1$d, you age is %2$d, others age is %3$d</string>
代碼中:
TextView tv_text = findViewById(R.id.tv_text); String text = getString(R.string.strings4, 20, 25, 30); tv_text.setText(text); Log.i(TAG, "text: "+text);
Log:
I/StringsApiUseDemoActivity: text: My age is 20, you age is 25, others age is 30
參考連接: