UI设计
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加qq表情" />
</LinearLayout>
MainActivity
package com.example.android_edittext1;
import java.lang.reflect.Field;
import java.util.Random;
import android.R.integer;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) this.findViewById(R.id.edittext);
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int randomId = 1 + new Random().nextInt(9);// 1到9随机数
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);
//定义需要处理的文本
SpannableString spannableString = new SpannableString(
"dashu");
//要让图片替代文字需要用ImageSpan对象
ImageSpan imageSpan = new ImageSpan(MainActivity.this,
bitmap);
//把文本的全部替换为表情图片
spannableString.setSpan(imageSpan, 0, 5,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//追加到editText
editText.append(spannableString);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
@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;
}
}