在TextView中想要動態的顯示某些值,用到%1$s,%1$d,先介紹一下:
%n$ms:代表輸出的是字符串,n代表是第幾個參數,設置m的值可以在輸出之前放置空格
%n$md:代表輸出的是整數,n代表是第幾個參數,設置m的值可以在輸出之前放置空格
%n$mf:代表輸出的是浮點數,n代表是第幾個參數,設置m的值可以控制小數位數,如m=2.2時,輸出格式為00.00
下面測試一下
1、
<string name="loading">離配置結束還剩%1$s秒</string>
String temp = getResources().getString(R.string.loading);
String timeTip = String.format(temp,60);
結果:離配置結束還剩60秒
2、
<string name="loading">離配置結束還剩%1$3s秒</string>
String temp = getResources().getString(R.string.loading);
String timeTip = String.format(temp,60);
結果:離配置結束還剩 60秒
注:m設置為3只有1個空格
3、
<string name="loading">離配置結束還剩%1$3s秒</string>
String temp = getResources().getString(R.string.loading);
String timeTip = String.format(temp,60);
結果:離配置結束還剩 60秒
注:m設置為10,有8個空格
4、
<string name="loading">離配置結束還剩%1$#4s秒</string>
String temp = getResources().getString(R.string.loading);
String timeTip = String.format(temp,60);
結果:app崩潰,拋出異常信息:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stringtest/com.example.stringtest.MainActivity}: java.util.FormatFlagsConversionMismatchException: %s does not support '#'
注:%s不支持設置#
5、
<string name="loading">離配置結束還剩%1$4d秒</string>
String temp = getResources().getString(R.string.loading);
String timeTip = String.format(temp,60);
結果:離配置結束還剩 60秒
注:m設置為4,有2個空格
6、
<string name="loading">離配置結束還剩%1$3.3f秒</string>
String temp = getResources().getString(R.string.loading);
String timeTip = String.format(temp,123456.123456);
結果:離配置結束還剩123456.123秒
注:m設置為3.3,小數位只取3位