Android中Textview显示Html,图文混排,支持图片点击放大

本文首发于网易云社区html


对于呈现Html文原本说,Android提供的Webview控件能够获得很好的效果,但使用Webview控件的弊端是效率相对比较低,对于呈现简单的html文本的话,杀鸡没必要使用牛刀。另外若是是在Listview中使用的Webview的话,效率则更是低下。android

    然而,Android还提供了android.text.Html类来支持Html的解析,利用这个类,咱们能够经过Textview来呈现Html文件。不过Html类并非只是全部的标签。Html的描述以下:web

This class processes HTML strings into displayable styledtext.canvas

Not all HTML tags are supported.缓存


1、解析Html标签异步

对于纯文字的Html文原本说,使用Textview来呈现很方便,一行代码就能够轻松搞定了,具体以下:ide

contentTextView.setText(Html.formHtml(htmlString));this


2、处理img图片标签,实现图文混排云计算

通常来讲,html文件经常是含有图片,若是须要在Textview中实现文字和图片的混排,须要使用ImageGetter。ImageGetter是Html类中一个接口,做用是给img标签获取图片内容,主要提供了一个getDrawable的方法。
url

/** 
* Retrieves images for HTML <img> tags.
*/  
public static interface ImageGetter {  
       /**
        * This methos is called when the HTML parser encounters an
        * <img> tag.  The <code>source</code> argument is the
        * string from the "src" attribute; the return value should be
        * a Drawable representation of the image or <code>null</code>
        * for a generic replacement image.  Make sure you call
        * setBounds() on your Drawable if it doesn't already have
        * its bounds set.
        */  
       public Drawable getDrawable(String source);  
}

解析来须要实现一个ImageGetter,具体以下:

public class MyImageGetter implements ImageGetter {  
     
   WeakReference<TextView> mTextViewReference;  
   Context mContext;  
 
   public MyImageGetter(Context context, TextView textView, int with) {  
       mContext = context.getApplicationContext();  
       mTextViewReference = new WeakReference<TextView>(textView);  
   }  
 
   @Override  
   public Drawable getDrawable(String url) {  
 
       URLDrawable urlDrawable = new URLDrawable(mContext);  
         
       // 异步获取图片,并刷新显示内容  
       new ImageGetterAsyncTask(url, urlDrawable).execute();  
 
       return urlDrawable;  
   }  
     
   public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {  
         
       WeakReference<URLDrawable> mURLDrawableReference;  
       String mUrl;  
 
       public ImageGetterAsyncTask(String url, URLDrawable drawable) {  
           mURLDrawableReference = new WeakReference<URLDrawable>(drawable);  
           mUrl = url;  
       }  
 
       @Override  
       protected Drawable doInBackground(String... params) {  
 
           // 下载图片,而且使用缓存  
           Bitmap bitmap = DownlaodUtils.getNetworkImageWithCache(mContext, mUrl);      
           BitmapDrawable bitmapDrawable = new BitmapDrawable(mContext.getResources(), bitmap);  
             
           Rect bounds = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());  
             
           if (mURLDrawableReference.get() != null) {  
               mURLDrawableReference.get().setBounds(bounds);  
           }  
           bitmapDrawable.setBounds(bounds);  
           return bitmapDrawable;  
       }  
 
       @Override  
       protected void onPostExecute(Drawable result) {  
           if (null != result) {  
               if (mURLDrawableReference.get() != null) {  
                   mURLDrawableReference.get().drawable = result;  
               }  
               if (mTextViewReference.get() != null) {  
                   // 加载完一张图片以后刷新显示内容  
                   mTextViewReference.get().setText(mTextViewReference.get().getText());  
               }  
           }  
       }  
   }  
     
     
   public class URLDrawable extends BitmapDrawable {  
       protected Drawable drawable;  
 
       public URLDrawable(Context context) {  
           // 设置默认大小和默认图片  
           Rect bounds = new Rect(0, 0, 100, 100);  
           setBounds(bounds);  
           drawable = context.getResources().getDrawable(R.drawable.default_image);  
           drawable.setBounds(bounds);  
       }  
 
       @Override  
       public void draw(Canvas canvas) {  
           if (drawable != null) {  
               drawable.draw(canvas);  
           }  
       }  
   }  
}  

实现了MyImageGetter以后,则须要实现图文混排就垂手可得了

  1. MyImageGetter imageGetter = new MyImageGetter(this, contentTextView);  

  2. contentTextView.setText(Html.formHtml(htmlString, imageGetter, null));  


、图片的点击放大

前面已经实现了Textview呈现html文本,而且可以图文混排。但不少状况下,须要支持点击图片后将图片放大显示。这样,咱们须要支持img标签的点击处理,可以监听到点击事件就能够实现这个功能了。这里咱们能够经过实现TagHandler接口来实现这个功能。首先看下android.text.Html类中的Taghandler接口:

/** 
    * Is notified when HTML tags are encountered that the parser does
    * not know how to interpret.
    */  
   public static interface TagHandler {  
       /**
        * This method will be called whenn the HTML parser encounters
        * a tag that it does not know how to interpret.
        */  
       public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader);  
}  


咱们只需实现TagHandler的handleTag方法来处理img标签则可,主要是给内容设置一个ClickableSpan,具体以下:

public class MyTagHandler implements TagHandler {  
 
   private mContext;  
     
   public MyTagHandler(Context context) {  
       mContext = context.getApplicationContext();  
   }  
     
   @Override  
   public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {  
 
       // 处理标签<img>  
       if (tag.toLowerCase(Locale.getDefault()).equals("img")) {  
           // 获取长度  
           int len = output.length();  
           // 获取图片地址  
           ImageSpan[] images = output.getSpans(len-1, len, ImageSpan.class);  
           String imgURL = images[0].getSource();  
             
           // 使图片可点击并监听点击事件  
           output.setSpan(new ClickableImage(mContext, imgURL), len-1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
       }  
   }  
     
   private class ClickableImage extends ClickableSpan {  
 
       private String url;  
       private Context context;  
         
       public ClickableImage(Context context, String url) {  
           this.context = context;  
           this.url = url;  
       }  
         
       @Override  
       public void onClick(View widget) {  
           // 进行图片点击以后的处理  
       }  
   }  
}  

实现了TagHandler以后,在formHtml传入实例则可:

MyImageGetter imageGetter = new MyImageGetter(this, contentTextView);  
MyTagHandler tagHandler = new MyTagHandler(this);  
contentTextView.setText(Html.formHtml(htmlString, imageGetter, tagHandler));  
contentTextView.setMovementMethod(LinkMovementMethod.getInstance());  



网易云产品免费体验馆,无套路试用,零成本体验云计算价值。  

本文来自网易云社区,经做者戚明峰受权发布


相关文章:
【推荐】 Windows扩展屏开发总结