EditTextFaceActivity .java
package cn.face;import java.lang.reflect.Field; //reflect 反射import java.util.Random;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.drawable.BitmapDrawable;import android.os.Bundle;import android.text.Spannable;import android.text.SpannableString;import android.text.style.ImageSpan;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class EditTextFaceActivity extends Activity { private EditText et_chat; private Button bt_insetFace; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); et_chat = (EditText)findViewById(R.id.et_chat); bt_insetFace = (Button)findViewById(R.id.bt_insetFace); bt_insetFace.setOnClickListener(new OnClickListener() { public void onClick(View v) { int randomId = 1+ new Random().nextInt(20); try{ Field field = R.drawable.class.getDeclaredField("face" + randomId); int resourceId = Integer.parseInt(field.get(null).toString()); //在android中显示图片信息,必须使用Bitmap位图对象来装载 Bitmap bitmap = BitmapFactory.decodeResource( getResources(), resourceId); ImageSpan imageSpan = new ImageSpan(EditTextFaceActivity.this,bitmap); SpannableString spannableString = new SpannableString("face"); //表情图片前缀为"face" spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); et_chat.append(spannableString); }catch(Exception e){ } } }); } }
看实现图片