EditText中如何输入自定义的表情图片呢,我们将实现的方法给大家分享一下。
这个例子是实现点击按钮,在文本控件中随机显示几个预订表情中的一个。
整体思路:产生一个随机数,用随机数和字符串拼成一个图片文件名(这里的字符串对于每一张图片是相同的,只是后面的数字不同);通过这个图片文件名找到对应的资源ID,将资源ID转换为位图;定义拆分字符串绑定位图,并把拆分字符串绑定到EditText控件上。
activity_main.xml文件:
<span style="color:#cc33cc;"> </span> <EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="添加qq表情"
android:layout_below="@id/edittext"
/>
MainActivity.java文件:
<span style="color:#cc33cc;"> </span>private Button button;
private EditText edittext;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
edittext=(EditText)findViewById(R.id.edittext);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//产生1-4的随机数,其中Random().nextInt(4)这个方法可以产生0-3的随机数
int randomId=1+new Random().nextInt(4);
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(MainActivity.this,bitmap);
//对字符串进行拆分的功能
SpannableString spannableString=new SpannableString("face");
spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
edittext.append(spannableString);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}