在TextView中显示表情图像和文字

最新在学习Android开发,在看Android开发权威指南,把书上的例子搬到自己博客上来,用来以后好查询

package com.luohaibo.testdemo01;

import java.lang.reflect.Field;




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

public class MainActivity extends Activity {
	
	public int getResourceId(String name){
		try {
			Field field = R.drawable.class.getField(name);
			return Integer.parseInt(field.get(null).toString());
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return 0;
	}
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		TextView textView = (TextView) findViewById(R.id.textview);
		//设置TextView的文字颜色
		textView.setTextColor(Color.BLACK);
		//设置TextView的背景颜色
		textView.setBackgroundColor(Color.WHITE);
		//设置TextView的字体大小
		textView.setTextSize(20);
		String html = "图像1<img src= 'image1'/> 图像2<img src='image2'/>图像3<img src='image3'/><p>";
		html += "图像4<a href='http://baidu.com'><img src='image4'/></a>图像5<img src='image5'/>";
		
		//使用Ttml.fromTtml方法转换包含Html标签的文本,需要指定fromHtml方法的第二个参数
		CharSequence charSequence = Html.fromHtml(html , new ImageGetter() {
			
			public Drawable getDrawable(String source) {
				// TODO Auto-generated method stub
				//装载图像资源
				Drawable drawable = getResources().getDrawable(getResourceId(source));
				
				// 第三个图像文件按50%等比压缩显示
				if(source.equals("image3"))
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth() /2, drawable.getIntrinsicHeight() /2);
				else  //其他图像文件按原大小显示
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
				
				return drawable;
			}
		} ,null);
		
		textView.setText(charSequence);
		
		// 只要使用了<a>标签,就需要设置MovementMethod对象,否则<a>标签出来显示效果,并不起任何作用
		textView.setMovementMethod(LinkMovementMethod.getInstance());
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

 

posted @ 2014-03-30 17:39  我是不可不戒  阅读(920)  评论(0编辑  收藏  举报