LoginSignup
3

More than 5 years have passed since last update.

自動でHTMLを表示するカスタムTextView

Last updated at Posted at 2016-04-14

素のTextViewで android:html="true" ができればいいんだけど。簡単すぎるからライブラリを使うまでもないけど、とりあえずこんな感じでできそう。android:text="..." に設定したタグが自動的にHTMLとして解釈されます。

Android Studioのlayout previewでもちゃんと反映されるのでデバッグも簡単。

import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.Spanned;
import android.util.AttributeSet;

public class HtmlView extends AppCompatTextView {

    public HtmlView(Context context) {
        this(context, null, 0);
    }

    public HtmlView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HtmlView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (text instanceof Spanned) {
            super.setText(text, type);
        } else {
            super.setText(Html.fromHtml(text.toString()), type);
        }
    }
}

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
3