今天学习 TextView 显示 html 但一直有一个问题就是图片显示不了
代码如下:
ImageGetter imgGetter = new Html.ImageGetter() { public Drawable getDrawable(String source) { Drawable drawable = null; URL url; try { url = new URL(source); drawable = Drawable.createFromStream(url.openStream(), ""); //获取网路图片 } catch (Exception e) { return null; } drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); return drawable; } }; Spanned html = Html.fromHtml(bodyData,imgGetter, null); TextView.setText(html);
就是这么一段代码,看起来好像没有问题,后来终于找到了原因:主要就是网络数据的获取在主线程上了
找到原因就好办了,把数据的获取部分放到子线程中去,这样就把问题解决了
ImageGetter imgGetter = new Html.ImageGetter() { public Drawable getDrawable(String source) { Drawable drawable = null; URL url; try { url = new URL(source); drawable = Drawable.createFromStream(url.openStream(), ""); //获取网路图片 } catch (Exception e) { return null; } drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); return drawable; } }; final Spanned html = Html.fromHtml(bodyData,imgGetter, null); runOnUiTread(new Runnable(){ public void run(){ TextView.setText(html); } });
利用获取出来的数据在用 runOnUiThread 传回主线程,也可以用Handler等,传回主线程就好。