package com.push.notif;
import java.lang.reflect.Field;
import java.util.Random;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ActivityA extends Activity implements OnClickListener {
private Button showExpression;
private EditText et;
private Button cancel;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.maina);
et = (EditText) findViewById(R.id.et);// 显示图文的EditView
showExpression = (Button) findViewById(R.id.button);// 点击显示表情的的button
cancel = (Button) findViewById(R.id.cancel);// 点击删除表情和文字的Button
showExpression.setOnClickListener(this);
cancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
int randomID = 1 + new Random().nextInt(28);
try {
// 表情文件统一放在了res/drawable文件下
Field field = R.drawable.class.getDeclaredField("face"
+ randomID);
int resouseId = Integer.parseInt(field.get(null).toString());
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
resouseId);
ImageSpan is = new ImageSpan(ActivityA.this, bitmap);//用ImageSpan指定图片替代文字
SpannableString ss = new SpannableString("[fac");// 其实写入EditView中的是这个字段“[fac”,表情图片会替代这个字段显示
// 如果为了区分表情可以写一个集合每个表情对应一段文字
ss.setSpan(is, 0, 4, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
et.append(ss);// 追加到EditView中
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.cancel:// 删除表情,当时表情时删除“[fac”的长度,是文字时删除一个长度
int selectionStart = et.getSelectionStart();// 获取光标的位置
if (selectionStart > 0) {
String body = et.getText().toString();
if (!TextUtils.isEmpty(body)) {
String tempStr = body.substring(0, selectionStart);
int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
if (i != -1) {
CharSequence cs = tempStr
.subSequence(i, selectionStart);
if (cs.equals("[fac")) {// 判断是否是一个表情
et.getEditableText().delete(i, selectionStart);
return;
}
}
et.getEditableText().delete(tempStr.length() - 1,
selectionStart);
}
}
break;
default:
break;
}
}
}