TextView的setText注意事項

##Do not concatenate text displayed with setText 當使用下面的方法對TextView進行setText時html

prodNameView.setText("" + name);  
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));

會有以下提示android

Do not concatenate text displayed with setText. Use resource string with placeholders.git

When calling TextView#setText:ide

  • Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits properly. Consider using String#format with proper format specifications (%d or %f) instead.
  • 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.
  • Do not build messages by concatenating text chunks. Such messages can not be properly translated.

簡單來講使用TextView的setText方法時,有三點要注意的:ui

  • 若是有數字,使用String#format方法來格式化
  • 別硬編碼,而是使用Android的String資源文件
  • 別使用+進行字符串拼接

##例子 在String資源文件中聲名編碼

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

在TextView中經過setText設置code

hello.setText(getString(R.string.welcome_messages,"John",10));

##參考 stackoverflow中的問題orm

Android官方文檔htm

相關文章
相關標籤/搜索