需求: TextView中顯示html 還要展示上面的圖片, 文字還好解決 直接調(diào)用
// html要顯示的文字
textView.setText(Html.fromHtml(html));
坑的是里面還要顯示圖片, 而且還不確定圖片的位置, 折騰了大半天, 在網(wǎng)上找到一個比較比較靠譜的方法, 特此記錄 :
@Deprecated
// 用到的方法 從提供的HTML字符串中返回可顯示樣式的文本,并使用遺留標(biāo)記
public static Spanned fromHtml(String source, ImageGetter imageGetter,TagHandler tagHandler) {
return fromHtml(source, FROM_HTML_MODE_LEGACY, imageGetter, tagHandler);
}
好了 直接上代碼 (ps: 可拿去直接用)
自定義ImageGetter類
public class MyImageGetter implements Html.ImageGetter {
private Context context;
String data;// 要加載的html內(nèi)容
TextView tv;// 加載html內(nèi)容的TextView控件
public MyImageGetter (Context context, TextView tv,
String data) {
this.context = context;
this.tv = tv;
this.data = data;
}
@Override
// 主要是重寫此方法
public Drawable getDrawable(String source) {
Drawable drawable = null;
if (source != null && source.length() > 0) {
// 截取圖片名稱 可根據(jù)自己的實際情況選擇
String imgName = source.substring(33, source.length());
// 圖片地址 我這因為后臺返回的是相對地址 需要我自己拼接
final String imgUrl= NetWork.BASE_URL + source.substring(2, source.length());
File file = new File(Environment.getExternalStorageDirectory(), imgName);
if (file.exists()) {
drawable = Drawable.createFromPath(file.getAbsolutePath());
if (drawable != null) {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 2, drawable.getIntrinsicHeight() * 2);
}
} else {
VolleyUtils.getNetworkImg(context, imgUrl, imgName, tv, data, this);
}
}
return drawable;
}
}
下載圖片 VolleyUtils 類
public class VolleyUtils {
/**
* 通過volley請求網(wǎng)絡(luò)圖片
* @param url
*/
public static void getNetworkImg(Context context, String url, final String name, final TextView tv,
final String data, final NetWorkImageGetter mNetWorkImageGetter) {
RequestQueue queue = Volley.newRequestQueue(context);
ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
saveMyBitmap(name, bitmap);
tv.setText(Html.fromHtml(data, mNetWorkImageGetter, null));
}
}, 0, 0, ImageView.ScaleType.CENTER, Bitmap.Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
/**
* 保存獲取到的網(wǎng)絡(luò)圖片到sdcard
* @param bitName
* @param mBitmap
*/
public static void saveMyBitmap(String bitName, Bitmap mBitmap) {
File f = new File("/sdcard/" + bitName);
try {
f.createNewFile();
} catch (IOException e) {
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用 實例:
MyImageGetter imageGetter = new MyImageGetter (this,
textView, html);
textView.setText(Html.fromHtml(html, imageGetter, null));
整個邏輯 : 先判斷本地是否存在對應(yīng)的圖片-->有 直接顯示 -->沒有從網(wǎng)上下載并保存到本地 .