1 public class MainActivity extends Activity { 2 private Handler handler; 3 private String html; 4 private TextView tv; 5 private ProgressBar bar; 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 // 网上找的html数据 11 html = "<html><head><title>TextView使用HTML</title></head><body><p><strong>强调</strong></p><p><em>斜体</em></p>" 12 + "<p><a href=\"http://www.jb51.net">超链接HTML入门</a>学习HTML!</p><p><font color=\"#aabb00\">颜色1" 13 + "</p><p><font color=\"#00bbaa\">颜色2</p><h1>标题1</h1><h3>标题2</h3><h6>标题3</h6><p>大于>小于<</p><p>" 14 + "下面是网络图片</p><img src=\"http://www.jb51.net/1207.jpg\"/></body>" 15 + "下面是网络图片</p><img src=\"http://www.jb51.net/207.jpg\"/></body></html>"; 16 tv = (TextView) this.findViewById(R.id.id); 17 bar = (ProgressBar) this.findViewById(R.id.id_bar); 18 tv.setMovementMethod(ScrollingMovementMethod.getInstance());// 滚动 19 handler = new Handler() { 20 @Override 21 public void handleMessage(Message msg) { 22 // TODO Auto-generated method stub 23 if (msg.what == 0x101) { 24 bar.setVisibility(View.GONE); 25 tv.setText((CharSequence) msg.obj); 26 } 27 super.handleMessage(msg); 28 } 29 }; 30 // 因为从网上下载图片是耗时操作 所以要开启新线程 31 Thread t = new Thread(new Runnable() { 32 Message msg = Message.obtain(); 33 @Override 34 public void run() { 35 // TODO Auto-generated method stub 36 bar.setVisibility(View.VISIBLE); 37 /** 38 * 要实现图片的显示需要使用Html.fromHtml的一个重构方法:public static Spanned 39 * fromHtml (String source, Html.ImageGetterimageGetter, 40 * Html.TagHandler 41 * tagHandler)其中Html.ImageGetter是一个接口,我们要实现此接口,在它的getDrawable 42 * (String source)方法中返回图片的Drawable对象才可以。 43 */ 44 ImageGetter imageGetter = new ImageGetter() { 45 @Override 46 public Drawable getDrawable(String source) { 47 // TODO Auto-generated method stub 48 URL url; 49 Drawable drawable = null; 50 try { 51 url = new URL(source); 52 drawable = Drawable.createFromStream( 53 url.openStream(), null); 54 drawable.setBounds(0, 0, 55 drawable.getIntrinsicWidth(), 56 drawable.getIntrinsicHeight()); 57 } catch (MalformedURLException e) { 58 // TODO Auto-generated catch block 59 e.printStackTrace(); 60 } catch (IOException e) { 61 // TODO Auto-generated catch block 62 e.printStackTrace(); 63 } 64 return drawable; 65 } 66 }; 67 CharSequence test = Html.fromHtml(html, imageGetter, null); 68 msg.what = 0x101; 69 msg.obj = test; 70 handler.sendMessage(msg); 71 } 72 }); 73 t.start(); 74 } 75 @Override 76 public boolean onCreateOptionsMenu(Menu menu) { 77 // Inflate the menu; this adds items to the action bar if it is present. 78 getMenuInflater().inflate(R.menu.main, menu); 79 return true; 80 } 81 }
时间: 2024-10-20 06:22:02