Textview显示HTML【图文混排】实现

废话不多说,直接上刺刀!

/**
     * 设置HTml网页
     *
     * @param text html字符串
     * @param view textview
     */
    private void setHtml(String text, TextView view) {
        MyImageGetter myImageGetter = new MyImageGetter(context, view);
        CharSequence sequence;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            sequence = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY, myImageGetter, null);
        } else {
            sequence = Html.fromHtml(text);
        }
        view.setText(sequence);
    }

其中MyImageGetter是自定义的类,用来显示html里面的图片,需要实现【Html.ImageGetter】这个方法是html里面自带的,我用的是glide,进行加载显示图片的。

这是我的写的

/**
 * 显示html里面的图片
 */
public class MyImageGetter implements Html.ImageGetter {
    private static final String TAG = "MyImageGetter";
    private TextView textView;
    private Context context;

    public MyImageGetter(Context context, TextView textView) {
        this.textView = textView;
        this.context = context;
    }

    @Override
    public Drawable getDrawable(final String source) {
        //在getDrawable中的source就是 img标签里src的值也就是图片的路径
        Log_Ma.e(TAG, source);
        LevelListDrawable drawable = new LevelListDrawable();//等级列表图片
        SimpleTarget<Bitmap> simpleTarget = new SimpleTarget<Bitmap>() {

            @Override
            public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                if (bitmap != null) {
                    BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), bitmap);
                    drawable.addLevel(1, 1, bitmapDrawable);
                    drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                    drawable.setLevel(1);
                    textView.invalidate();
                    textView.setText(textView.getText());//解决图文重叠
                }
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);

            }
        };
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.banner_place)//占位图片
                .error(R.mipmap.banner_place)//错误图片
                .fallback(R.mipmap.banner_place);

        Glide.with(context)
                .asBitmap()
                .load(source)
                .apply(options)
//                .override(400, 400)//压缩图片
                .into(simpleTarget);
        return drawable;
    }

这样就可以显示图片了,当时我们项目里面并没有显示点击的效果,就先这样搞了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值