简体   繁体   中英

TextView with HTML content - Hide images/empty squares

I have html content and setting this into (android) textbox as follows

textbox.setText(Html.fromHtml(myhtml));

HTML content contains some img tags as well, I do not want display images, currently it displays empty square boxes where ever there is a img tag. How do I hide those square boxes?

You could do a regex replace <img.+?> on htmlString.

textView.setText(Html.fromHtml(htmlString.replaceAll("<img.+?>", "")));

Untested

Update:

since images can look like:

<img ...></img>

and

<img... />

This solution will match both cases:

String htmlBody = htmlString.replaceAll("<img.+/(img)*>", "");
textView.setText(Html.fromHtml(htmlBody));

This works

Create Html.ImageGetter to return empty image as follows

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;

public class EmptyImageGetter implements Html.ImageGetter {
    private static final Drawable TRANSPARENT_DRAWABLE = new ColorDrawable(Color.TRANSPARENT);

    @Override
    public Drawable getDrawable(String source) {
        return TRANSPARENT_DRAWABLE;
    }
}

and then create a static instance

private static final EmptyImageGetter EMPTY_IMAGE_GETTER = new EmptyImageGetter();

set this into text view

textView.setText(Html.fromHtml(myhtml, EMPTY_IMAGE_GETTER, null));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM