欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现TextView显示HTML加图片的方法

程序员文章站 2024-03-05 17:14:19
本文实例讲述了android实现textview显示html加图片的方法。分享给大家供大家参考,具体如下: textview显示网络图片,我用android2.3的系统,...

本文实例讲述了android实现textview显示html加图片的方法。分享给大家供大家参考,具体如下:

textview显示网络图片,我用android2.3的系统,可以显示图片出来,并且如果图片比较大,应用会卡的现象,肯定是因为使用主线程去获取网络图片造成的,但如果我用android4.0以上的系统运行,则不能显示图片,只显示小方框。

究其原因,是在4.0的系统上执行的时候报错了,异常是:android.os.networkonmainthreadexception 经过查文档,原来是4.0系统不允许主线程(ui线程)访问网络,因此导致了其异常。说白了就是在主线程*问网络,会造成主线程挂起,系统不允许使用了。

此处有作部分修改,代码独立。图片实现异步加载。解决上述问题
用法,调用代码activity

//textview 控件
textviewcontent = (textview) getactivity().findviewbyid(r.id.textview_prodcut_detail_more_zp_content);
//html文本
zp_content = "测试图片信息:<br><img src=\"http://b2c.zeeeda.com/upload/2013/05/10/136814766742544.jpg\" />";
//默认图片,无图片或没加载完显示此图片
drawable defaultdrawable = mainactivity.ma.getresources().getdrawable(r.drawable.stub);
//调用
spanned sp = html.fromhtml(zp_content, new htmlimagegetter(textviewcontent, "/esun_msg", defaultdrawable), null);
textviewcontent.settext(sp);

htmlimagegetter类:

import java.io.inputstream;
import android.graphics.canvas;
import android.graphics.drawable.bitmapdrawable;
import android.graphics.drawable.drawable;
import android.os.asynctask;
import android.os.environment;
import android.text.html.imagegetter;
import android.util.log;
import android.widget.textview;
public class htmlimagegetter implements imagegetter{
  private textview _htmltext;
  private string _imgpath;
  private drawable _defaultdrawable;
  private string tag = "htmlimagegetter";
  public htmlimagegetter(textview htmltext, string imgpath, drawable defaultdrawable){
    _htmltext = htmltext;
    _imgpath = imgpath;
    _defaultdrawable = defaultdrawable;
  }
  @override
  public drawable getdrawable(string imgurl) {
    string imgkey = string.valueof(imgurl.hashcode());
    string path = environment.getexternalstoragedirectory() + _imgpath;
    fileutil.createpath(path);
    string[] ss = imgurl.split("\\.");
    string imgx = ss[ss.length-1];
    imgkey = path+"/" + imgkey+"."+imgx;
    if(fileutil.exists(imgkey)){
      drawable drawable = fileutil.getimagedrawable(imgkey);
      if(drawable != null){
        drawable.setbounds(0, 0, drawable.getintrinsicwidth(), drawable.getintrinsicheight());
        return drawable;
      }else{
        log.v(tag,"load img:"+imgkey+":null");
      }
    }
    urldrawable urldrawable = new urldrawable(_defaultdrawable);
    new asyncthread(urldrawable).execute(imgkey, imgurl);
    return urldrawable;
  }
  private class asyncthread extends asynctask<string, integer, drawable> {
    private string imgkey;
    private urldrawable _drawable;
    public asyncthread(urldrawable drawable){
      _drawable = drawable;
    }
    @override
    protected drawable doinbackground(string... strings) {
      imgkey = strings[0];
      inputstream inps = network.getinputstream(strings[1]);
      if(inps == null) return _drawable;
      fileutil.savefile(imgkey, inps);
      drawable drawable = drawable.createfrompath(imgkey);
      return drawable;
    }
    public void onprogressupdate(integer... value) {
    }
    @override
    protected void onpostexecute(drawable result) {
      _drawable.setdrawable(result);
      _htmltext.settext(_htmltext.gettext());
    }
  }
  public class urldrawable extends bitmapdrawable {
    private drawable drawable;
    public urldrawable(drawable defaultdraw){
      setdrawable(defaultdraw);
    }
    private void setdrawable(drawable ndrawable){
      drawable = ndrawable;
      drawable.setbounds(0, 0, drawable.getintrinsicwidth(), drawable
          .getintrinsicheight());
      setbounds(0, 0, drawable.getintrinsicwidth(), drawable
          .getintrinsicheight());
    }
    @override
    public void draw(canvas canvas) {
      drawable.draw(canvas);
    }
  }
}

network 类:

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.httpurlconnection;
import java.net.malformedurlexception;
import java.net.url;
import java.util.hashmap;
import java.util.iterator;
import java.util.map;
import java.util.zip.gzipinputstream;
import java.util.zip.inflaterinputstream;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.entity.bufferedhttpentity;
import org.apache.http.impl.client.defaulthttpclient;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.util.log;
public class network {
  private static string tag = "network";
  public static string gethttpdata(string baseurl){
    return gethttpdata(baseurl, "get", "", null);
  }
  public static string posthttpdata(string baseurl, string reqdata){
    return gethttpdata(baseurl, "post", reqdata, null);
  }
  public static string posthttpdata(string baseurl, string reqdata, hashmap<string, string> propertys){
    return gethttpdata(baseurl, "post", reqdata, propertys);
  }
  /**
   * 获取赛事信息
   * @return
   */
  public static string gethttpdata(string baseurl, string method, string reqdata, hashmap<string, string> propertys){
    string data = "", str;
    printwriter outwrite = null;
    inputstream inpstream = null;
    bufferedreader reader = null;
    httpurlconnection urlconn = null;
    try{
      url url = new url(baseurl);
      urlconn = (httpurlconnection)url.openconnection();
      //启用gzip压缩
      urlconn.addrequestproperty("accept-encoding", "gzip, deflate");
      urlconn.setrequestmethod(method);
      urlconn.setdooutput(true);
      urlconn.setconnecttimeout(3000);
      if(propertys != null && !propertys.isempty()){
        iterator<map.entry<string, string>> props = propertys.entryset().iterator();
        map.entry<string, string> entry;
        while (props.hasnext()){
          entry = props.next();
          urlconn.setrequestproperty(entry.getkey(), entry.getvalue());
        }
      }
      outwrite = new printwriter(urlconn.getoutputstream());
      outwrite.print(reqdata);
      outwrite.flush();
      urlconn.connect();
      //获取数据流
      inpstream = urlconn.getinputstream();
      string encode = urlconn.getheaderfield("content-encoding");
      //如果通过gzip
      if(encode !=null && encode.indexof("gzip") != -1){
        log.v(tag, "get data :" + encode);
        inpstream = new gzipinputstream(inpstream);
      }else if(encode != null && encode.indexof("deflate") != -1){
        inpstream = new inflaterinputstream(inpstream);
      }
      reader = new bufferedreader(new inputstreamreader(inpstream));
      while((str = reader.readline()) != null){
        data += str;
      }
    }catch (malformedurlexception ex){
      ex.printstacktrace();
    }catch (ioexception ex){
      ex.printstacktrace();
    }finally{
      if(reader !=null && urlconn!=null){
        try {
          outwrite.close();
          inpstream.close();
          reader.close();
          urlconn.disconnect();
        } catch (ioexception ex) {
          ex.printstacktrace();
        }
      }
    }
    log.d(tag, "[http data]["+baseurl+"]:" + data);
    return data;
  }
  /**
   * 获取image信息
   * @return
   */
  public static bitmap getbitmapdata(string imgurl){
    bitmap bmp = null;
    log.d(tag, "get imgage:"+imgurl);
    inputstream inpstream = null;
    try{
      httpget http = new httpget(imgurl);
      httpclient client = new defaulthttpclient();
      httpresponse response = (httpresponse)client.execute(http);
      httpentity httpentity = response.getentity();
      bufferedhttpentity bufferedhttpentity = new bufferedhttpentity(httpentity);
      //获取数据流
      inpstream = bufferedhttpentity.getcontent();
      bmp = bitmapfactory.decodestream(inpstream);
    }catch (exception ex){
      ex.printstacktrace();
    }finally{
      if(inpstream !=null){
        try {
          inpstream.close();
        } catch (ioexception ex) {
          ex.printstacktrace();
        }
      }
    }
    return bmp;
  }
  /**
   * 获取url的inputstream
   * @param urlstr
   * @return
   */
  public static inputstream getinputstream(string urlstr){
    log.d(tag, "get http input:"+urlstr);
    inputstream inpstream = null;
    try{
      httpget http = new httpget(urlstr);
      httpclient client = new defaulthttpclient();
      httpresponse response = (httpresponse)client.execute(http);
      httpentity httpentity = response.getentity();
      bufferedhttpentity bufferedhttpentity = new bufferedhttpentity(httpentity);
      //获取数据流
      inpstream = bufferedhttpentity.getcontent();
    }catch (exception ex){
      ex.printstacktrace();
    }finally{
      if(inpstream !=null){
        try {
          inpstream.close();
        } catch (ioexception ex) {
          ex.printstacktrace();
        }
      }
    }
    return inpstream;
  }
}

fileutil类:

import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import android.graphics.drawable.bitmapdrawable;
import android.graphics.drawable.drawable;
import android.os.environment;
import android.util.log;
public class fileutil {
  private static int file_size = 4*1024;
  private static string tag = "fileutil";
  public static boolean hassdcard(){
    string status = environment.getexternalstoragestate();
    if(status.equals(environment.media_mounted)){
      return true;
    }
    return false;
  }
  public static boolean createpath(string path){
    file f = new file(path);
    if(!f.exists()){
      boolean o = f.mkdirs();
      log.i(tag, "create dir:"+path+":"+o.tostring());
      return o;
    }
    return true;
  }
  public static boolean exists(string file){
    return new file(file).exists();
  }
  public static file savefile(string file, inputstream inputstream){
    file f = null;
    outputstream outsm = null;
    try{
      f = new file(file);
      string path = f.getparent();
      if(!createpath(path)){
        log.e(tag, "can't create dir:"+path);
        return null;
      }
      if(!f.exists()){
        f.createnewfile();
      }
      outsm = new fileoutputstream(f);
      byte[] buffer = new byte[file_size];
      while((inputstream.read(buffer)) != -1){
        outsm.write(buffer);
      }
      outsm.flush();
    }catch (ioexception ex) {
      ex.printstacktrace();
      return null;
    }finally{
      try{
        if(outsm != null) outsm.close();
      }catch (ioexception ex) {
        ex.printstacktrace();
      }
    }
    log.v(tag,"[fileutil]save file:"+file+":"+boolean.tostring(f.exists()));
    return f;
  }
  public static drawable getimagedrawable(string file){
    if(!exists(file)) return null;
    try{
      inputstream inp = new fileinputstream(new file(file));
      return bitmapdrawable.createfromstream(inp, "img");
    }catch (exception ex){
      ex.printstacktrace();
    }
    return null;
  }
}

更多关于android相关内容感兴趣的读者可查看本站专题:《android编程之activity操作技巧总结》、《android资源操作技巧汇总》、《android文件操作技巧汇总》、《android操作sqlite数据库技巧总结》、《android操作json格式数据技巧总结》、《android数据库操作技巧总结》、《android编程开发之sd卡操作方法汇总》、《android开发入门与进阶教程》、《android视图view技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。