[Android]解決TextView.setTextヒントsetTextで表示されるテキストを連結しないでください。リソース文字列を使用する



Solve Textview



背景を掘る

実際のプロジェクト開発プロセスでは、よく使用します TextView.setText() 単位を設定しながらメソッドを実行した場合 時刻を設定するxxxxxxxx日 または設定 Xxkg体重 *の場合、通常、次の表現を使用します。

// Set the current date TextView tvDate = (TextView) findViewById(R.id.main_tv_date) tvDate.setText ( 'Current Date:' + year + 'of' + month + 'month' + day + 'day') // display the current weight value is provided TextView tvWeight = (TextView) findViewById(R.id.main_tv_weight) tvWeight.setText ( 'current weight:' + weight + 'kg')

したがって... Android Studioで開発している場合、テキスト設定にこのモードを使用すると、次のヒントが表示されます。




問題分析

さて、問題は強迫性障害の患者の大多数、これに耐えられない完璧主義者の地図にあると私は信じています、そして私たちはそれをどのように行うかを最後に見たいと思います私たちは拷問することはできません! ! !によって与えられたメッセージの最初の分析として:



Do not concatenate text displayed with setText. Use resource string with placeholders. [less...](#lint/SetTextI18n) (Ctrl+F1 Alt+T) Do not connect display text using setText method using string resources with placeholders (prompt us to try to use to display text strings strings.xml). When calling TextView#setText When using a TextView # setText method * Never call Number#toString() to format numbers it will not handle fraction separators and locale-specific digits * Not used Number # toString () in digital format it does not process the digital fractional separator and specific regions properly. properly. Consider using String#format with proper format specifications (%d or %f) instead. Use, string format (% d or% f) instead. * Do not pass a string literal (e.g. 'Hello') to display text. Hardcoded text can not be properly translated to Do not pass string literals (for example: 'Hello') to display text. Hard-coded text can not be correctly translated into other languages. other languages. Consider using Android resource strings instead. Consider using Android resource string. * Do not build messages by concatenating text chunks. Such messages can not be properly translated. Do not create a block of text messages through the connection. Such information can not be properly translated.

上記の情報から、次のことがわかります。

  • Numer.toString()を使用して文字列を変換するモードは推奨されません。文字列は正規形式(%dまたは%f)を使用することをお勧めします。
  • 文字列リテラルを直接使用してテキストを直接表示することはお勧めしません。Androidの直接文字列リソースを使用することをお勧めします。
  • 提案メッセージのテキストブロックは、接続を介して表示されません。

解決

上記の問題の分析を読むと、同様の問題が発生します。この警告は、TextView.setText()メソッドを使用した次の方法で発生する可能性があります。

  • String.formatメソッドを使用する
  • ステートメントに続くStrings.xml(たとえば、ここで日付に設定)
the current date:% 1 $ d of% 2 $ d month% 3 $ d day
  • そのような使用コード
// Set the current date 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パラメーターの位置は形式に対応します。
$ sは数値文字列を表します$ Dは整数値を表します$ Fは浮動小数点値を表します。
as:%1 $ dは、最初のパラメーター値が整数型であることを表します。



  • Android文字列リソースを使用して文字列リテラルを置き換えます