【菜鳥學安卓】- TextView 顯示Html 一 解決圖片顯示不了的小問題
阿新 • • 發佈:2019-02-11
今天學習 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等,傳回主執行緒就好。