Html.fromHtml(url,imageGetter,TagHandler)重寫ImageGetter 異步加載圖片,加載圖片之後重置TextView(EditView)的內容。
參數說明:source=需要展示的html文本內容,imageGetter=需要繼承Html.ImageGetter接口實現邏輯,tagHandler=這個參數表示,當textView解析遇到無法識別的html標籤是否發送通知或者消息,如果遇到無法解析的標籤,該方法將會被調用。這個沒有具體測試過,一般賦值null。
問題:1網絡圖片的加載不能阻塞主線程,因此需要異步加載 (ImageLoader 會好些 有緩存機制)
2加載圖片之後無法正常顯示(偏小) (使用Drawable.createFromResourceStream)
3重新設置圖片大小之後在個別系統上會出現圖片錯位(這個暫時無法解決,還望有解決辦法的共享一下解決思路)(沒復現)
代碼:
UrlDrawable :可以讓你加載圖片的時候顯示初始的圖片,也就是加載中的圖片。
public class URLDrawable extends BitmapDrawable {
protected Drawable drawable;
@Override
public void draw (Canvas canvas) {
if (drawable != null ) {
drawable.draw(canvas);
}
}
}
UrlParser :重寫ImageGetter.
public class URLImageParser implements Html .ImageGetter {
Context context;
EditText container ;
public URLImageParser(EditText editText, Context c) {
this .context = c;
this .container = editText;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask <String , Void , Drawable > {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable drawable) {
this .urlDrawable = drawable;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0 ];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
if (result != null ){
urlDrawable.setBounds(0 , 0 , result.getIntrinsicWidth(), result.getIntrinsicHeight());
urlDrawable.drawable = result;
URLImageParser.this .container .invalidate();
URLImageParser.this .container .setHeight(URLImageParser.this .container .getHeight() + result.getIntrinsicHeight());
URLImageParser.this .container .setEllipsize(null );
}
}
public Drawable fetchDrawable(String urlString) {
try {
URL url = new URL(urlString);
Drawable drawable = Drawable.createFromResourceStream(context.getResources() , null ,url.openStream(), "src" , null );
if (drawable!= null ){
drawable.setBounds(0 , 0 , drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}else {
return null ;
}
} catch (Exception e) {
return null ;
}
}
}
}
使用textView加載帶網絡圖片的html內容需求是可以實現的,但是由於html支持的標籤有限,自己實現會很複雜,例如自定義字體顏色、span標籤等都不能很好的支持,所以選擇了webview展示,相對於EditView來說,不可編輯但是展示效果和處理比EditView的效果好,不需要自己寫需要解析的標籤(坑)。圖文並茂的頁面還是使用webView比較好,但是webView是不是就完美解決了呢?然而並不是,畢竟webView加載頁面是頁面的內容,效果沒有Android原生的好,同事使用webView加載頁面在Android系統4.4+開始滑動頁面會有明顯的卡頓和跳幀,有些簡直無法接受。
使用騰訊X5SDK優化webView加載騰訊X5SDK能夠加速webView加載,優化滑動卡頓,效果還是比較明顯的(沒測),只是使用條件比較苛刻,在國內使用的APP還是可以考慮。
實現圖文混排的另一種方式,不是對img標籤
1.spanString
(http://blog.csdn.net/feizhixuan46789/article/details/10334441)