我正在使用 fromHTML 将 HTML 文本加载到 RecyclerView 元素内的 TextView 中。这确实有效,但是由于从 URL 加载图像并且设置或更新适配器时应用程序冻结或崩溃并且我收到日志说在主线程上完成了太多工作,因此速度非常慢。有什么方法可以使我正在使用的 HTML.fromHTML 中的 ImageGetter 更高效,并在更新时使适配器在单独的线程上运行,这样它就不会冻结应用程序?我试过寻找更快的方法来获取 Drawable,但主要的图像加载库似乎没有办法返回 Drawable 对象。
图像获取器:
private Html.ImageGetter Images = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels;
int screenW = (int) dpWidth;
Drawable drawable;
FetchImageUrl fiu = new FetchImageUrl(context ,source);
try {
Boolean result = fiu.execute().get();
drawable = fiu.getImage();
//Log.i("source",""+source);
//Log.i("source",""+drawable);
}catch (Exception e) {
Log.e("Error",""+e);
drawable = ContextCompat.getDrawable(activity, R.drawable.image_not_found);
}
if(drawable!=null) {
final float scalingFactor =
(float) (screenW-300) / drawable.getIntrinsicWidth();
drawable.setBounds(0, 0, (screenW-300),
(int) (drawable.getIntrinsicHeight() * scalingFactor));
}
return drawable;
}
};
获取图片网址:
private class FetchImageUrl extends AsyncTask<String, String, Boolean> {
private String imageUrl;
private Drawable image;
public FetchImageUrl(Context context, String url) {
this.imageUrl = url;
image = null;
}
public Drawable getImage()
{
return image;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... args) {
try {
InputStream input_stream = (InputStream) new URL(imageUrl).getContent();
image = Drawable.createFromStream(input_stream, "src name");
return true;
}
catch (Exception e)
{
Log.e("Exception",""+e);
image = null;
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
}
}