Android的TextView中显示图片和图像的方法

实现效果如下:(感谢老罗视频的讲解)  视频下载地址:猛击这里

没事多看看 不同过的实现方案还是不错的。就是在Textview中嵌套点图片显示出来。效果不错。有人该说,你这傻逼,闲着蛋疼了一会用着用那的。呵呵。其实呢这种方法可以避免布局中混乱嵌套的问题,你只需要搞个Textview和复制点图片进Drawable文件夹下即可实现一些功能了。不需要那么麻烦。要不然你得嵌很多布局也很麻烦。

 

代码如下:

package lixiaodaoaaa.com.ui;

import java.lang.reflect.Field;

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

/***
 * by lixiaodaoaaa Tecent_weibo: http://t.qq.com/lixiaodaoaaa
 * xinlang_Weibo:http://weibo.com/lixiaodaoaaa
 * 
 * @author lixiaodaoaaa
 * 
 */
public class MainActivity extends Activity
{

	/**
	 * 此方法是通过资源的名字 获得资源的id;比如在Drawable文件夹下的face_01.png 获得face_01.png的id;;;;;
	 * 主要用到了R.drawable.class.getField 通过反射的方法。
	 * 
	 * @param name
	 * @return
	 */
	public int gerResouceIdByName(String name)
	{
		try
		{
			Field field = R.drawable.class.getField(name);
			return Integer.parseInt(field.get(null).toString());
		} catch (Exception e)
		{
			System.out.println("parse fialed  return 0 is here");
		}
		return 0;
	}

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

	private void initTextView()
	{
		TextView textView = (TextView) findViewById(R.id.tv_test01);
		textView.setBackgroundColor(Color.WHITE);
		textView.setTextColor(Color.BLACK);
		textView.setTextSize(20);
		String html1 = "图像1 <img src='face_01' /><p>";
		html1 += "图像2 <img src='face_02' /><p>";
		html1 += "图像3 <img src='face_03' /><p><p>";// <p>这里是段落标记。让他在回车换行下面显示;;;
		html1 += "图像4 <a href='http://weibo.com/lixiaodaoaaa'><img src='face_04' /></a><p>";
		html1 += "图像5 <img src='face_05' />";

		CharSequence charSequence = Html.fromHtml(html1, new ImageGetter()
		{
			@Override
			public Drawable getDrawable(String name)
			{
				int currentDrawableId = gerResouceIdByName(name);// 通过名字得到资源的id;
				Drawable drawable = getResources().getDrawable(currentDrawableId);
				// 必须对返回的drawable 设置 bounds 要不然不会显示;;;
				if (name.equals("face_03"))
				{
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 3, drawable.getIntrinsicHeight() / 3);
				}
				// 如果是图片03的话我们 将进行简单的缩放,设置为它原来的一半大小;;;
				else if (name.equals("face_04"))
				{
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 2, drawable.getIntrinsicHeight() * 2);
					// 如果是图表4的话我们将他倍宽倍高 设置放大;;;
				} else
				{
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
				}
				return drawable;
			}
		}, null);
		textView.setText(charSequence);
	}

}

源码下载地址 :猛击这里下载
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值