Android如何在TextView中顯示圖片

 大傢好,今天和大傢分享如何在TextView中加入圖片的功能,有兩種方式,第一種是繼承TextView實現圖片通過重寫來實現圖片的顯示功能,第二種是利用現成的api實現圖片的顯示功能。我們知道TextView支持部分HTML標簽,但是想在TextView中加入圖片則怎麼做呢?直接通過<img src=""/>標簽肯定是不行的。通過查看API我們發現有這樣一個靜態的方法:
[java] <span style="font-family:SimSun;font-size:16px;">public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) </span> 
<span style="font-family:SimSun;font-size:16px;">public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) </span>那麼是不是隻要實現其中的Html.ImageGetter就可以加入圖片呢?答案是肯定的!

還是別廢話吧,代碼最直觀

[java]<span style="font-family:SimSun;font-size:16px;">package org.winplus.demo; 
 
import android.app.Activity; 
import android.graphics.drawable.Drawable; 
import android.os.Bundle; 
import android.text.Html; 
import android.text.Html.ImageGetter; 
import android.widget.TextView; 
 
public class TextViewDemoActivity extends Activity { 
 
    private TextView txtWecome; 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        setupViews(); 
    } 
 
    private void setupViews() { 
        txtWecome = (TextView) findViewById(R.id.wecome); 
        txtWecome.append(Html.fromHtml("<img src='"+R.drawable.tangcheng_ok+"'/>", imageGetter, null)); 
    } 
 
    ImageGetter imageGetter = new ImageGetter() { 
 
        @Override 
        public Drawable getDrawable(String source) { 
            int id = Integer.parseInt(source); 
            Drawable drawable = getResources().getDrawable(id); 
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight()); 
            return drawable; 
        } 
    }; 
}</span> 
<span style="font-family:SimSun;font-size:16px;">package org.winplus.demo;

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

public class TextViewDemoActivity extends Activity {

 private TextView txtWecome;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  setupViews();
 }

 private void setupViews() {
  txtWecome = (TextView) findViewById(R.id.wecome);
  txtWecome.append(Html.fromHtml("<img src='"+R.drawable.tangcheng_ok+"'/>", imageGetter, null));
 }

 ImageGetter imageGetter = new ImageGetter() {

  @Override
  public Drawable getDrawable(String source) {
   int id = Integer.parseInt(source);
   Drawable drawable = getResources().getDrawable(id);
   drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
   return drawable;
  }
 };
}</span>
這是效果圖:

 

 

摘自 秋風的博客

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。