我們在許多的App軟件中都能使用表情包,只要選擇你想輸入的表情就會將表情添加到你的編輯框,那麼這種效果是怎麼實現的?下面我們就對實現的原理解析解析,先上效果圖:
想必有些朋友看到圖片就發現了是怎麼實現了的吧,我們一般使用setText的方法都是隻傳入一個String的格式數據,其實Android在設計的時候就考慮到了圖片的情況,它提供給我們可傳入的數據是一個CharSequence類型,String類型正是它的子類。我們需要的圖片類型也有對應的子類,SpannableString就是這樣一個類型。下面給出程序代碼:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.test.MainActivity" >
<EditText
android:id="@+id/edit"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="5"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/image"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ue412"/>
</LinearLayout>
<Button
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查看EditText的內容"
android:onClick="onClick"/>
</LinearLayout>
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText edit;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit=(EditText) findViewById(R.id.edit);
image=(ImageView) findViewById(R.id.image);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//獲取ImageSpan對象
ImageSpan span=new ImageSpan(image.getDrawable());
//創建SpannableString對象,用於替換需要顯示的表情圖片
SpannableString spannableString=new SpannableString("\\cry");
spannableString.setSpan(span, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//在原來的文本內容上添加表情圖片到EditText
edit.append(spannableString);
}
});
}
public void onClick(View v){
//查看EditText的輸入內容
Toast.makeText(this, "內容爲:"+edit.getText().toString(), Toast.LENGTH_SHORT).show();
}
}