当前位置:操作系统 > 安卓/Android >>

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>
这是效果图:

 \

 




摘自 秋风的博客
补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,