EditText實現輸入表情,edittext實現表情
EditText實現輸入表情
一、簡介
editText是TextView的子類,TextView能用的工具EditText都能用,這裡就是editText利用SpannableString的ImageSpan實現輸入表情的功能
類結構圖:
二、方法
1)EditText利用SpannableString的ImageSpan實現添加表情的方法
第一步:建立SpannableString對象spannableString
SpannableString spannableString=new SpannableString("d");
第二步:利用SpannableString的setSpan方法添加imageSpan
ImageSpan imageSpan=new ImageSpan(this, BitmapFactory.decodeResource(getResources(),R.drawable.image1));
spannableString.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
第三步:在EditText對象中添加spannableString
et_emotion.append(spannableString);
三、代碼執行個體
:
代碼:
fry.Activity01
1 package fry; 2 3 4 import com.example.editTextDemo1.R; 5 6 import android.app.Activity; 7 import android.graphics.BitmapFactory; 8 import android.os.Bundle; 9 import android.text.Spannable;10 import android.text.SpannableString;11 import android.text.style.ImageSpan;12 import android.view.View;13 import android.view.View.OnClickListener;14 import android.widget.Button;15 import android.widget.EditText;16 17 public class Activity01 extends Activity implements OnClickListener{18 private EditText et_emotion;19 private Button bt_addEmotion;20 @Override21 protected void onCreate(Bundle savedInstanceState) {22 // TODO Auto-generated method stub23 super.onCreate(savedInstanceState);24 setContentView(R.layout.activity01);25 et_emotion=(EditText) findViewById(R.id.et_emotion);26 bt_addEmotion=(Button) findViewById(R.id.bt_addEmotion);27 bt_addEmotion.setOnClickListener(this);28 }29 @Override30 public void onClick(View arg0) {31 // TODO Auto-generated method stub32 /*33 * EditText利用SpannableString的ImageSpan實現添加表情的方法34 * 第一步:建立SpannableString對象spannableString35 * 第二步:利用SpannableString的setSpan方法添加imageSpan36 * 第三步:在EditText對象中添加spannableString37 * 38 */39 SpannableString spannableString=new SpannableString("d");40 ImageSpan imageSpan=new ImageSpan(this, BitmapFactory.decodeResource(getResources(),R.drawable.image1));41 spannableString.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);42 et_emotion.append(spannableString);43 }44 }
/editTextDemo1/res/layout/activity01.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <EditText 8 android:id="@+id/et_emotion" 9 android:layout_width="match_parent"10 android:layout_height="wrap_content"11 android:ems="10" >12 13 <requestFocus />14 </EditText>15 16 <Button17 android:id="@+id/bt_addEmotion"18 android:layout_width="match_parent"19 android:layout_height="wrap_content"20 android:text="Button" />21 22 </LinearLayout>