我们在许多的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();
}
}