TextViewで一部の文字列の色を簡単に変更する方法
例えば、以下の文字列を表示するとします。
日本語の場合
新品2点 \1,200より
英語の場合
2 new from \1,200
この\1,200という部分を赤くしたいのですが、英語と日本語では文字の並び順が違うので、TextViewを別々にするとかなり面倒なことになります。
これを簡単にできないかなーと思ってやってみた方法が以下です。
layoutのxml
<TextView android:id="@+id/main_textView_sample1" android:layout_width="fill_parent" android:layout_height="wrap_content" />
TextViewを定義してるだけです
<string name="test" formatted="false">%s new from %s</string>
values-ja/string.xml
<string name="test" formatted="false">新品%s点 %sより</string>
日本語と英語でそれぞれ用意します
Activity
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView text = (TextView)findViewById(R.id.main_textView_sample1); String s = String.format(getText(R.string.test).toString(), "2", "\1,200"); text.setText(s); }
そこで、Html.fromHtml()というメソッドがあるようで、つかえるhtmlタグには制限があるもののfontタグは使えるようなのでこれを使用します
http://developer.android.com/intl/ja/reference/android/text/Html.html
string.xmlの文字列にfontタグを追加します
values/string.xml
<string name="test" formatted="false">%s new from <font color=\"red\">%s</font></string>
values-ja/string.xml
<string name="test2" formatted="false">新品%s点 <font color=\"red\">%s</font>より</string>
ActivityはsetTextする箇所で、Html.fromHtml()というメソッドを使用します
text.setText(Html.fromHtml(s));
これを使って、取消線ができるか期待したのですがsタグは使えないみたいです。。