問題背景
在實際的項目開發過程中,我們會經常用到TextView.setText()方法,而在進行某些單位設置時,比如 設置時間xxxx年xx月xx日 或者設置 體重xx公斤* 時,大家一般都會使用如下寫法:
// 設置顯示當前日期
TextView tvDate = (TextView) findViewById(R.id.main_tv_date);
tvDate.setText("當前日期:" + year + "年" + month + "月" + day + "日");
// 設置顯示當前體重數值
TextView tvWeight = (TextView) findViewById(R.id.main_tv_weight);
tvWeight.setText("當前體重:" + weight + "公斤");
那么...如果你是在Android Studio上進行開發的話,你在使用該方式進行文本設置時就會看到以下提示:
setText_waring.png
問題分析
Ok,相信上圖的問題是絕大多數的強迫癥患者、完美主義者所不能容忍的,那么我們就來看看它到底想要怎么做才能夠不折磨咱們?。。∠确治鯝S給出的提示信息:
Do not concatenate text displayed with setText. Use resource string with placeholders. [less...](#lint/SetTextI18n) (Ctrl+F1 Alt+T)
請勿使用setText方法連接顯示文本.用占位符使用字符串資源(提示我們盡量使用strings.xml的字符串來顯示文本)。
When calling TextView#setText
當使用TextView#setText方法時
* Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits
* 不使用Number#toString()格式的數字;它不會正確地處理分數分隔符和特定于地區的數字。
properly. Consider using String#format with proper format specifications (%d or %f) instead.
考慮使用規范格式(%d或%f)的字符串來代替。
* Do not pass a string literal (e.g. "Hello") to display text. Hardcoded text can not be properly translated to
不要通過字符串文字(例如:“你好”)來顯示文本。硬編碼的文本不能被正確地翻譯成其他語言。
other languages. Consider using Android resource strings instead.
考慮使用Android資源字符串。
* Do not build messages by concatenating text chunks. Such messages can not be properly translated.
不要通過連接建立消息文本塊。這樣的信息不能被正確的翻譯。
通過以上信息,我們可以得知:
- 不建議使用Numer.toString()的方式來進行字符串的轉換,建議使用規范格式(%d或%f)的字符串來代替;
- 不建議直接使用字符串文字來直接顯示文本,建議直接使用Android字符串資源;
- 不建議通過連接的方式顯示消息文本塊。
解決方法
通過上述對問題的分析解讀,我們上述類似問題所引發的警告可以通過如下方式更規范化的使用TextView.setText()方法:
- 使用String.format方法
- 在strings.xml中進行如下聲明(這里以日期設置為例)
<string name="current_time">當前日期:%1$d年%2$d月%3$d日</string>
- 在代碼中這樣使用
// 設置顯示當前日期
TextView tvDate = (TextView) findViewById(R.id.main_tv_date);
tvDate.setText(String.format(getResources().getString(R.string.current_time),year,month,day));
String.format常用格式說明:
%n 代表當前為第幾參數,使strings.xml中的位置與format參數的位置對應;
d代表為整數數值;
d代表第一個參數,數值類型為整數。
- 使用Android字符串資源來替換字符串文字
看到這里,是不是徹底了解如何改造了?既然都懂了,那我的贊呢?
TIM截圖20170620112603.png