android text中显示HTML语言
1 package com.example.test; 2 3 import java.io.InputStream; 4 import java.net.URL; 5 import android.annotation.SuppressLint; 6 import android.app.Activity; 7 import android.graphics.drawable.Drawable; 8 import android.os.Build; 9 import android.os.Bundle; 10 import android.os.StrictMode; 11 import android.text.Html; 12 import android.text.Html.ImageGetter; 13 import android.text.method.LinkMovementMethod; 14 import android.text.method.ScrollingMovementMethod; 15 import android.widget.TextView; 16 17 public class MainActivity extends Activity { 18 TextView tView; 19 Drawable drwable = null; 20 21 @SuppressLint("NewApi") 22 @Override 23 protected void onCreate(Bundle savedInstanceState) { 24 super.onCreate(savedInstanceState); 25 setContentView(R.layout.main); 26 if (Build.VERSION.SDK_INT >= 10) { 27 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); 28 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); 29 } 30 31 tView = (TextView) findViewById(R.id.testText); 32 // HTML文本 33 String html = "<html><head><title>TextView使用HTML</title></head><body><p><strong>强调</strong></p><p><em>斜体</em></p>" 34 + "<p><a href=\"http://www.dreamdu.com/xhtml/\">超链接HTML入门</a>学习HTML!</p><p><font color=\"#aabb00\">颜色1" 35 + "</p><p><font color=\"#00bbaa\">颜色2</p><p><font color=\"#aabb00\">颜色1" 36 + "</p><p><font color=\"#00bbaa\">颜色2</p><p><font color=\"#aabb00\">颜色1" 37 + "</p><p><font color=\"#00bbaa\">颜色2</p><p><font color=\"#aabb00\">颜色1" 38 + "</p><p><font color=\"#00bbaa\">颜色2</p><p><font color=\"#aabb00\">颜色1" 39 + "</p><p><font color=\"#00bbaa\">颜色2</p><h1>标题1</h1><h3>标题2</h3><h6>标题3</h6><p>大于>小于<</p><p>" 40 + "下面是网络图片</p><img src=\"http://avatar.csdn.net/0/3/8/2_zhang957411207.jpg\"/></body></html>"; 41 42 tView.setMovementMethod(ScrollingMovementMethod.getInstance());// 设置可滚动 43 tView.setMovementMethod(LinkMovementMethod.getInstance());// 设置超链接可以打开网页 44 tView.setText(Html.fromHtml(html, imgGetter, null)); 45 } 46 47 // 这里面的resource就是fromhtml函数的第一个参数里面的含有的url 48 ImageGetter imgGetter = new Html.ImageGetter() { 49 public Drawable getDrawable(String source) { 50 InputStream is = null; 51 try { 52 is = (InputStream) new URL(source).getContent(); 53 Drawable d = Drawable.createFromStream(is, "src"); 54 d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 55 is.close(); 56 return d; 57 } catch (Exception e) { 58 return null; 59 } 60 } 61 }; 62 63 }
posted on 2014-06-12 10:05 clarenceV1 阅读(645) 评论(0) 编辑 收藏 举报