在AndroidStudio中,當(dāng)我們用TextView用下面方式顯示字符串時:
tvTime.setText(time++ "''");
然后android會給出警告"Do not concatenate text displayed with setText"。
當(dāng)然AS會提示你解決辦法:"use resource string with placeholders"
,告訴我們要使用占位符。
在String資源文件里面加上:
<string name="show_time">"%1$d''"</string>
java代碼如下:
tvTime.setText( mContext.getString(R.string.show_time,time));
可是為什么我們最好不要在TextView的setText方法里面拼接字符串顯示 ?
首先要明白不能直接在setText里面做的事情:
- 不要用數(shù)字的toString來格式化它,它不會正確處理分?jǐn)?shù)分隔符和特定區(qū)域的數(shù)字.考慮使用String.format來使用的格式化它(%d or %f) 。
- 避免使用硬編碼來顯示字符串,硬編碼字符串不能合適的轉(zhuǎn)化成其它語言.
- 不要使用字符串拼接信息,這樣字符串信息不能被合適的轉(zhuǎn)譯。就像硬編碼一樣。
這也就是為什么不能"concatenate text displayed with setText".