gpt4 book ai didi

android - 在 Android 上使用 TextView 和 Html.ImageGetter 异步显示图像?

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:21 25 4
gpt4 key购买 nike

我想用 SpannableString 设置一个 TextView,它来自下面的方法:

Html.fromHtml(String source, Html.ImageGetter imageGetter, 
Html.TagHandler tagHandler)

但是这里的ImageGetter需要重写下面的方法:

public abstract Drawable getDrawable(String source)

因为我需要从互联网上获取 drawable,所以我必须异步执行它,但似乎不是。

如何让它发挥作用?谢谢。

最佳答案

这些人做得很好,这是我使用 Square 的 Picasso 库的解决方案:

//...
final TextView textView = (TextView) findViewById(R.id.description);
Spanned spanned = Html.fromHtml(getIntent().getStringExtra(EXTRA_DESCRIPTION),
new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources().getDrawable(R.drawable.abc_btn_check_material);;
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new ImageGetterAsyncTask(DetailActivity.this, source, d).execute(textView);

return d;
}
}, null);
textView.setText(spanned);
//...


class ImageGetterAsyncTask extends AsyncTask<TextView, Void, Bitmap> {


private LevelListDrawable levelListDrawable;
private Context context;
private String source;
private TextView t;

public ImageGetterAsyncTask(Context context, String source, LevelListDrawable levelListDrawable) {
this.context = context;
this.source = source;
this.levelListDrawable = levelListDrawable;
}

@Override
protected Bitmap doInBackground(TextView... params) {
t = params[0];
try {
Log.d(LOG_CAT, "Downloading the image from: " + source);
return Picasso.with(context).load(source).get();
} catch (Exception e) {
return null;
}
}

@Override
protected void onPostExecute(final Bitmap bitmap) {
try {
Drawable d = new BitmapDrawable(context.getResources(), bitmap);
Point size = new Point();
((Activity) context).getWindowManager().getDefaultDisplay().getSize(size);
// Lets calculate the ratio according to the screen width in px
int multiplier = size.x / bitmap.getWidth();
Log.d(LOG_CAT, "multiplier: " + multiplier);
levelListDrawable.addLevel(1, 1, d);
// Set bounds width and height according to the bitmap resized size
levelListDrawable.setBounds(0, 0, bitmap.getWidth() * multiplier, bitmap.getHeight() * multiplier);
levelListDrawable.setLevel(1);
t.setText(t.getText()); // invalidate() doesn't work correctly...
} catch (Exception e) { /* Like a null bitmap, etc. */ }
}
}

我的 2 美分...和平!

关于android - 在 Android 上使用 TextView 和 Html.ImageGetter 异步显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3758535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com