I am currently working on a simple chat application. I want to add emoticons features in this app. I already have a function to receive string from other users. What I want is-
It can easily be implemented by using SpannableString Here is a sample implementation in code.
package com.jslan.nabin.emosample;
import android.graphics.drawable.Drawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText textBox = (EditText) findViewById(R.id.textBox);//I have created an EditText named textBox in activity_main.xml
Drawable d;
ImageSpan span;
String abc = "some :D message :D";
SpannableString ss = new SpannableString(abc);
for(int i = 0; i<abc.length();i++){//loop to check presence of other emoji strings.
if (abc.contains(":D")){
int startSpan = abc.indexOf(":D");
d = getResources().getDrawable(R.drawable.laugh); // I have kept laugh.png of size 24x24 in drawable folder.
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, startSpan, startSpan+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
abc = abc.replaceFirst(":D"," "); //replace with two blank spaces.
}
//to check other types of emoji, use else if ladder and place the similar code.
}
textBox.append(ss);
}
}
You can try like this
if (rosan.contains(":p")){
int span = abc.indexOf(":p");
res = getResources().getDrawable(R.drawable.myImage);
res.setBounds(0, 0, res.getIntrinsicWidth(), res.getIntrinsicHeight());
span = new ImageSpan(res, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, startSpan, startSpan+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
rosan = rosan.replaceFirst(":D"," "); //replace with two blank spaces.
}