1. 程式人生 > >android基礎--TextView.Do not concatenate text displayed with setText. Use resource string with placeho

android基礎--TextView.Do not concatenate text displayed with setText. Use resource string with placeho

我們在使用TextView顯示內容的過程中,經常遇到需要顯示的內容只有少許引數需要改變,比如:
距離過年還有xx天xx時xx秒,當我們在更新TextView的內容時,一般是這麼寫的:

TextView mTextView = this.findViewById(R.id.mTextView);
mTextView.setText("距離過年還有"+mDay+"天"+mMinute+"時"+mSecond+"秒");
如果你是用Android Studio開發的話,那麼它應該送你以下的警告:

Do not concatenate text displayed with setText,use resource string with placeholders
[撇腳翻譯:應使用資源字串來顯示文字佔位符],這裡所說的就是mDay、mMinute、mSecond這些變量了。
當然對於這些警告我們其實可以不理它們,它只是告訴我們這樣寫不規範,但如果我們要消除這個警告,
可以使用以下的實現:
string.xml中的資源宣告

<string name="delay_time">距離過年還有%1$d天%2$d時%3$d秒</string>
在程式碼中的使用:

mTextView.setText(String.format(getResources().getString(R.string.delay_time),mDay,mMinute,mSecond));
常用格式:
%n$s--->n表示目前是第幾個引數 (比如%1$s中的1代表第一個引數),s代表字串
%n$d--->n表示目前是第幾個引數 (比如%1$d中的1代表第一個引數),d代表整數
%n$f--->n表示目前是第幾個引數 (比如%1$f中的1代表第一個引數),f代表浮點數
--------------------- 
作者:BunToy 
來源:CSDN 
原文:https://blog.csdn.net/xiabing082/article/details/54092357 
版權宣告:本文為博主原創文章,轉載請附上博文連結!