您的位置:首页 > 移动开发 > Android开发

Android编程开发之EditText实现输入QQ表情图像的方法

2015-12-28 15:42 1046 查看

实现效果如下:

将QQ表情图像放到res下的drawable-hdpi文件夹下:

布局文件:

<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:inputType="text">
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/edittext"
android:layout_alignRight="@+id/edittext"
android:layout_below="@+id/edittext"
android:layout_marginTop="38dp"
android:text="添加QQ表情" />

MainActivity.java:

package com.example.edittext1;
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.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Menu;
import android.view.View;
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) findViewById(R.id.edittext);
button=(Button) findViewById(R.id.button1);
//为按钮注册点击事件
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//产生随机数 随机数是从0开始,所以要加1,这样就会产生1到9的随机数
int randomId=1+new Random().nextInt(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);
//要让图片替代指定的文字就要用ImageSpan
ImageSpan imageSpan = new ImageSpan(MainActivity.this, bitmap);
SpannableString spannableString = new SpannableString("face");//face就是图片的前缀名
spannableString.setSpan(imageSpan, 0, 4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.append(spannableString);
} catch ( Exception e) {
}
}
});
}
@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;
}
}

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:

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