代码改变世界

EditText输入表情图像

2014-03-20 20:01  kingshow  阅读(1324)  评论(0编辑  收藏  举报

 

      EditText中添加表情图像。EditText是在开发当中经常用到的控件,大家都比较熟悉了,通过学习老罗的视频,在这里记录一下,以便以后方便查阅。

一、建立工程

 

二、activity_main.xml中代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText 
        android:id="@+id/edittext1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        />
    <Button 
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="添加QQ表情"
        />
    
</LinearLayout>
View Code

三、MainActivity.java中的代码

package com.study.android_edittext;

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

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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)this.findViewById(R.id.edittext1);
        button = (Button)this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                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 = 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
                }
                
            }
        });
        
    }


    @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;
    }
    
}
View Code

四、效果图