[安卓]textView加载HTML-异步加载网络图片

tech2023-01-08  108

1.创建异步加载图片类

import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LevelListDrawable; import android.os.AsyncTask; import android.text.Html; import android.widget.TextView; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import cn.akbigdata.smartauxiliarypolice.R; /** * html图片异步加载 */ public class HtmlImageGetter implements Html.ImageGetter { private TextView contentTv; private Context mContext; public HtmlImageGetter(Context context, TextView textView) { mContext = context; contentTv = textView; } @Override public Drawable getDrawable(String source) { LevelListDrawable d = new LevelListDrawable(); Drawable empty = mContext.getResources().getDrawable(R.drawable.police_photo); d.addLevel(0, 0, empty); d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight()); new LoadImage().execute(source, d); return d; } /** * 异步下载网络图片 */ class LoadImage extends AsyncTask<Object, Void, Bitmap> { private LevelListDrawable mDrawable; @Override protected Bitmap doInBackground(Object... params) { String source = (String) params[0]; mDrawable = (LevelListDrawable) params[1]; try { InputStream is = new URL(source).openStream(); return BitmapFactory.decodeStream(is); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 图片下载完成后执行 * @param bitmap */ @Override protected void onPostExecute(Bitmap bitmap) { if (bitmap != null) { BitmapDrawable d = new BitmapDrawable(mContext.getResources(), bitmap); mDrawable.addLevel(1, 1, d); /** * 适配图片大小 <br/> * 默认大小:bitmap.getWidth(), bitmap.getHeight()<br/> * 适配屏幕:getDrawableAdapter */ mDrawable = getDrawableAdapter(mContext, mDrawable, bitmap.getWidth(), bitmap.getHeight()); mDrawable.setLevel(1); //刷新视图 contentTv.invalidate(); //避免多图片重叠 CharSequence t = contentTv.getText(); contentTv.setText(t); } } /** * 加载网络图片,适配大小 * @param context * @param drawable * @param oldWidth * @param oldHeight * @return */ public LevelListDrawable getDrawableAdapter(Context context, LevelListDrawable drawable, int oldWidth, int oldHeight) { LevelListDrawable newDrawable = drawable; long newHeight = 0;// 未知数 int newWidth = context.getResources().getDisplayMetrics().widthPixels;// 默认屏幕宽 newHeight = (newWidth * oldHeight) / oldWidth; newDrawable.setBounds(0, 0, newWidth, (int) newHeight); return newDrawable; } } }

2. 使用

TextView content = findViewById(R.id.content); content.setText(Html.fromHtml(intent.getStringExtra("content"), new HtmlImageGetter(this, content), null));
最新回复(0)