android中string.xml中%1$s、%1$d等的用法


在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位


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM