安卓控件使用系列5:EditText输入表情图片

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
				}
			}
		});
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值