您的位置:首页 > 其它

TextView显示表情图像和文字

2014-03-17 21:01 429 查看
通过TextView显示出表情图像和文字。

一、建立工程,在drawable下放入五张表情图片

package com.study.android_textview2;

import java.lang.reflect.Field;

import android.R.drawable;
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 {
//根据资源的ID的变量名获得Field的对象,使用反射机制实现的
Field field = R.drawable.class.getField(name);
//取得并返回资源的id的字段(静态变量)的值,使用反射机制
return Integer.parseInt(field.get(null).toString());

} catch (Exception e) {
e.printStackTrace();
}
return 0;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView)this.findViewById(R.id.textview);
textView.setTextColor(Color.BLACK);
textView.setBackgroundColor(Color.WHITE);
textView.setTextSize(20);
String html = "图像1<img src='image1'/>图像2<img src='image2'/>图像3<img src='image3'/><p>";
html += "图像4<a href='http://www.baidu.com'><img src='image4'/></a>图像5<img src='image5'/>";
CharSequence charSequence = Html.fromHtml(html, new ImageGetter() {

@Override
public Drawable getDrawable(String source) {
//获得系统资源的信息,比如图片信息
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);
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;
}

}


View Code
四、效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: