TextViewのtextにHTMLを使用しようとしても、普通に行うとHTMLタグは効きません(文字列としてそのまま出力されます)。
HTMLタグを有効にするにはandroid.text.Html#fromHtmlを使います。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TextView textView = (TextView) findViewById(R.id.someview); | |
String htmlText = "<p>HTMLタグを使って<strong>強調</strong>したい"; | |
/* 普通にsetTextに渡した場合はHTMLタグは無視される(文字列としてそのまま表示される) */ | |
textView.setText(htmlText); | |
// この場合の出力は | |
// 「<p>HTMLタグを使って<strong>強調</strong>したい」になり、タグは効かない | |
/* android.text.Html#fromHtmlを使ってタグを効かせる */ | |
CharSequence formedHtmlText = Html.fromHtml(htmlText); | |
textView.setText(formedHtmlText); | |
// この場合の出力は<p>タグも<strong>タグも効いて文字列としては「HTMLタグを使って強調したい」になる |
また、strings.xmlにHTMLを記述するためには、<、>、&、"をエスケープ表記する必要があります。先の文例で考えるなら、以下のようになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<string name="html_text"><p>HTMLタグを使って<strong>強調</strong>したい</string></string> | |
<!-- なお、 など&を持つ値を使いたい場合は &nbsp; のように記述する --> |
0 件のコメント:
コメントを投稿