TextView中動態顯示某些值
前言:在某些場景下我們希望TextView通過引用string中的資源,但是某些值,如金額,性別等是隨着場景的變化而變化的。在這種情況下,你就需要用到佔位符%1$s
,%1$d
了。下文是轉載“弘文館校書”的博客。原文博客地址:http://www.cnblogs.com/Eric-zhao/p/5230007.html。
在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位