Android中实现Edittext中输入表情图片的方法

废话不说,直接上效果:

Android中实现Edittext中输入表情图片的方法_第1张图片

相关代码如下:

package weibo.lixiaodaoaaa.ui;

import java.lang.reflect.Field;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
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 MainActivity extends Activity implements OnClickListener
{

	/**
	 * ******************腾讯微博: http://t.qq.com/lixiaodaoaaa ***************
	 * ******************新浪微博:http://weibo.com/lixiaodaoaaa ***************
	 * ******************by:lixiaodaoaaa ***********************
	 */

	private Context context;
	private Button btn1;
	private EditText et1;

	public int getRandomResourceId()
	{
		try
		{
			int randmId = new Random().nextInt(7) + 1;
			Field field = R.drawable.class.getDeclaredField("face_0" + randmId + "");
			return field.getInt(null);
		} catch (Exception e)
		{
			e.printStackTrace();
			System.out.println("error is here");
		}
		return 0;
	}
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initAllDatas();
		for (int i = 0; i < 100; i++)
		{
			btn1.performClick();
		}
	}

	private void initAllDatas()
	{
		context = MainActivity.this;
		btn1 = (Button) findViewById(R.id.btn1);
		et1 = (EditText) findViewById(R.id.et1);
		btn1.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.btn1:
			ImageSpan imageSpan = new ImageSpan(context, BitmapFactory.decodeResource(getResources(),
					getRandomResourceId()));
			SpannableString spannableString = new SpannableString("face");
			spannableString.setSpan(imageSpan, 0, spannableString.length(), SpannableString.SPAN_MARK_MARK);
			et1.append(spannableString);
			break;
		default:
			break;
		}
	}
}

源码工程文件下载地址 : 猛击这里

你可能感兴趣的:(EditText中输入表情图片)