Android TextView使用HTML处理字体样式、显示图片等

String类是CharSequence的子类,在CharSequence子类中有一个接口Spanned,即类似html的带标记的文本,我们可以用它来在TextView中显示html
android.text.Html类共提供了三个方法:
<span style="font-size:18px;">public static Spanned fromHtml (String source)
(上面只能显示纯文本内容)
public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
(上面这个方法可以显示在html里面包含图片的内容)
public static String toHtml (Spanned text)</span>
对于第二种显示 ,安卓4.0以后的写法必须将更新UI放到子线程去实现,所以最总的写法为

package com.example.demo;


import java.net.URL;


import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.widget.TextView;


public class MainActivity extends Activity {


    private Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView view = (TextView) findViewById(R.id.tv);
        final String sText = "测试图片信息:<br><img src=\"http://b.hiphotos.baidu.com/image/h%3D200/sign=9d3833093f292df588c3ab158c305ce2/d788d43f8794a4c274c8110d0bf41bd5ad6e3928.jpg\" />";
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Spanned text = Html.fromHtml(sText, imgGetter, null);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        view.setText(text);
                    }
                });
            }
        }).start();


    }


    private ImageGetter imgGetter = new Html.ImageGetter() // 格式语句不一定相同,只要进行网络加载图片即可
    {
        public Drawable getDrawable(String source) {
            Drawable drawable = null;
            try {
                drawable = Drawable.createFromStream(
                        new URL(source).openStream(), "");
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable  
                        .getIntrinsicHeight());
            } catch (Exception e) {
                return new Drawable() {
                    public void setColorFilter(ColorFilter cf) {
                    }


                    public void setAlpha(int alpha) {
                    }


                    public int getOpacity() {
                        return 0;
                    }


                    public void draw(Canvas canvas) {
                    }
                };
            }
            return drawable;
        }
    };


}





你可能感兴趣的:(Android TextView使用HTML处理字体样式、显示图片等)