简体   繁体   English

从 TextView (Kotlin) 中的 html 内容下载和缓存内联图像的现代方法

[英]Modern way to download and caching inline images from html content inside TextView (Kotlin)

According to this question , I used the following two classes to download the images inside (HTML content <img tag), but not too efficient for some reasons, first sometimes it's not to cache all images, second the static Picasso field causes a leak in the app, so I looking for a better way and support kaolin for sure根据这个问题,我使用以下两个类来下载里面的图像(HTML内容<img标签),但由于某些原因效率不高,首先有时它不是缓存所有图像,其次static Picasso字段导致泄漏该应用程序,所以我正在寻找更好的方法并肯定支持高岭土

PicassoCache毕加索缓存

public class PicassoCache {

//    @SuppressLint("StaticFieldLeak")
    private static Picasso picassoInstance = null;

    private PicassoCache(Context context) {

        Downloader downloader = new OkHttp3Downloader(context, Integer.MAX_VALUE);
        Picasso.Builder builder = new Picasso.Builder(context);
        builder.downloader(downloader);
        picassoInstance = builder.build();
    }

    public static Picasso getPicassoInstance(Context context) {

        if (picassoInstance == null) {

            //noinspection InstantiationOfUtilityClass
            new PicassoCache(context);
            return picassoInstance;
        }

        return picassoInstance;
    }
}

PicassoImageGetter毕加索ImageGetter


public class PicassoImageGetter implements Html.ImageGetter {

    private static final String TAG = "PicassoImageGetter";

    private TextView textView = null;
    Context mContext;

    public PicassoImageGetter(TextView target, Context context) {
        textView = target;
        mContext = context;
    }

    public PicassoImageGetter() {

    }

    @Override
    public Drawable getDrawable(String source) {
        BitmapDrawablePlaceHolder drawable = new BitmapDrawablePlaceHolder();
//        Picasso.get().load(source).into(drawable);
        PicassoCache.getPicassoInstance(mContext)
                .load(source)
                .priority(Picasso.Priority.HIGH)
                .error(R.drawable.no_image)
                .into(drawable);

        return drawable;

    }

    @SuppressWarnings("deprecation")
    private class BitmapDrawablePlaceHolder extends BitmapDrawable implements com.squareup.picasso.Target {
        protected Drawable drawable;
        @Override
        public void draw(final Canvas canvas) {
            if (drawable != null) {
                drawable.draw(canvas);
            }
        }

        public void setDrawable(Drawable drawable) {
                this.drawable = drawable;
                int width = drawable.getIntrinsicWidth();
                int height = drawable.getIntrinsicHeight();
                drawable.setBounds(0, 0, width, height);
                setBounds(0, 0, width, height);
            if (textView != null) {
                textView.setText(textView.getText());
            }
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            setDrawable(new BitmapDrawable(mContext.getResources(), bitmap));
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
            setDrawable(errorDrawable);
            Log.e(TAG, "onBitmapFailed: "+e.toString() );
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }

    }
}

and I used it like this我像这样使用它

val imageGetter = PicassoImageGetter(binding.blogContent, this)
        val html: Spannable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY, imageGetter, null) as Spannable
        } else {
            Html.fromHtml(content, imageGetter, null) as Spannable
        }
        binding.blogContent.text = html

Result结果

结果

I found this library html-textview sufficientlysecure.htmltextview.HtmlTextView我发现这个库html-textview sufficientlysecure.htmltextview.HtmlTextView secure.htmltextview.HtmlTextView

the dependency依赖

in project Gradle file:在项目 Gradle 文件中:

repositories {
    jcenter()
}

in App Gradle file:在应用程序 Gradle 文件中:

dependencies {
implementation 'org.sufficientlysecure:html-textview:3.9'
}

Inside XML file replace your textView with:在 XML 文件中,将您的 textView 替换为:

<org.sufficientlysecure.htmltextview.HtmlTextView
      android:id="@+id/allNewsBlockTextView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="2dp"
      android:textColor="#000"
      android:textSize="18sp"
      app:htmlToString="@{detailsViewModel.selectedText}" />

there's one problem the project has been stopped.有一个问题项目已停止。 4.0 is the last release and there's no more update/maintaining, I'll use it until I found a better solution 4.0 是最后一个版本,没有更多更新/维护,我会一直使用它,直到找到更好的解决方案

Take a look at the accepted answer to this question on how to replace a placeholder in an HTML string processed by Html or HtmlCompat .看看这个问题的公认答案,关于如何替换由HtmlHtmlCompat处理的 HTML 字符串中的占位符。 (The sample project in the answer awarded the bounty has a slightly improved solution.) You would need to replace the simulateNetworkFetch() function with another that actually does a network fetch. (授予赏金的答案中的示例项目有一个稍微改进的解决方案。)您需要用另一个实际进行网络获取的simulateNetworkFetch() function 替换。 (This was just a demo for the answer.) (这只是答案的演示。)

For efficiently fetching images from a network, I suggest that you take a look at the Glide library .为了有效地从网络中获取图像,我建议您查看Glide 库 There are tutorials available online on how to to implement Glide into a project.网上有关于如何在项目中实现Glide的教程。 I am sure the Picasso has similar functionality, but I don't have any experience with it.我确信毕加索有类似的功能,但我没有任何经验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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