Android TextView Html.formHtml()

Keywords: Android



TextView is easy to display in HTML, but it is complicated to display in the text. This paper uses Glide as the image loading tool.

Get started

1, First look at what you need

public void onSuccess(String string) {
        CharSequence charSequence;
        // This is a custom ImageGetter
        DetailImageGetter detailImageGetter = new DetailImageGetter(this,textView);
        //Since fromHtml becomes obsolete at api24, version judgment is added
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            charSequence = Html.fromHtml(string, Html.FROM_HTML_MODE_LEGACY,
                    detailImageGetter, null);
        } else {
            charSequence = Html.fromHtml(string, detailImageGetter, null);

2, Take a look at the custom ImageGetter class:

class DetailImageGetter implements Html.ImageGetter {
    private Context context;
    private TextView textView;

    DetailImageGetter(Context context, TextView textView) {
        this.context = context;
        this.textView = textView;

    public Drawable getDrawable(String source) {
        final UrlDrawable drawable = new UrlDrawable();
                .into(new SimpleTarget<Bitmap>() {
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        drawable.setBounds(0, 0, resource.getWidth(), resource.getHeight());
        return drawable;

    private class UrlDrawable extends BitmapDrawable {
        private Bitmap bitmap;

        public void draw(Canvas canvas) {
            if (bitmap != null) {
                canvas.drawBitmap(bitmap, 0, 0, getPaint());

        void setBitmap(Bitmap bitmap) {
            this.bitmap = bitmap;

It contains a custom BitmapDrawable class. If the onDraw method is not rewritten, the image will not be displayed, only a space of image size will be there.

At this point, the download and display of the images are completed, and the Glide is used for caching. But there is another problem. The empty constructor of BitmapDrawable is obsolete, but when I use the constructor BitmapDrawable (RES, bitmap), the image cannot be loaded. According to the source code, it is only found that the incoming res has updated the mTargetDensity. I don't know why it can't be displayed. I hope you can give some guidance.

Posted by mattmate on Fri, 03 Jul 2020 08:58:24 -0700