LoginSignup
19
16

More than 5 years have passed since last update.

TextViewにHTMLタグを使用して表示する

Last updated at Posted at 2012-07-24

<font color>タグなどが使える。
<img>タグも使える。サイズは解像度に応じて要調整かも知れない。

改行はもちろん<br>にしておく必要あり。
strings.xmlでの記述は要注意。

// 文字列データ
static final String sampleHtml ="色を<font color=\"red\">変える</font>サンプル";

TextView text = (TextView)findViewById(R.id.text1);
text.setText(Html.fromHtml(sampleHtml));

// strings.xml
TextView text2 = (TextView)findViewById(R.id.text2);
String src = getString(R.string.htmlstring);
text2.setText(Html.fromHtml(src));
strings.xml
<string name="htmlstring">リソース文字列は&lt;font color=&quot;green&quot;&gt;タグ記号に要注意&lt;/font&gt;</string>

imgタグの場合、srcに指定したものに応じた処理を書く必要がある(ImageGetterインターフェースを実装すする)。
R.drawableのidを指定することももちろんできる。

ic_launcher.pngを埋め込む場合のstrings.xml
<string name="imgstring">イメージは&lt;img src="ic_launcher" &gt;ファイル名をそのままでおk</string>
使用例:imgタグの場合
// htmlタグを解析してイメージを返すために必要。
ImageGetterImpl imageGetter = new ImageGetterImpl(getApplicationContext());

// img.png
TextView text3 = (TextView)findViewById(R.id.text3);
String html = getResources().getString(R.string.imgstring);
Spanned message = Html.fromHtml(html, imageGetter, null);
text3.setText(message);
ImageGetterImpl.java

/**
 * htmlタグを解析してイメージを返せるようにする
 * @author S.Kamba
 *
 */
public class ImageGetterImpl implements ImageGetter {

    Context mContext = null;

    public ImageGetterImpl(Context context){
        mContext = context;
    }

    @Override
    public Drawable getDrawable(String source) {
        // sourceにimgタグの src=""で指定した内容が渡される

        Resources res = mContext.getResources();
        // 画像のリソースIDを取得
        int id = res.getIdentifier(source, "drawable", mContext.getPackageName());

        // リソースIDから Drawable のインスタンスを取得
        Drawable d = res.getDrawable(id);

        // 取得した元画像のサイズを取得し、必要なら、表示画像のサイズを調整する
        int w = d.getIntrinsicWidth();
        int h = d.getIntrinsicHeight();
        if(source.equals("ic_launcher")){
            w = (int)(w*0.58f);
            h = (int)(h*0.58f);
        }
        d.setBounds(0, 0, w, h);

        return d;
    }
}

aタグのリンクに反応させるには、次の一文が必要。

textview.setMovementMethod(LinkMovementMethod.getInstance());
19
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
16