我目前正在开发一个简单的聊天应用程序。我想在这个应用程序中添加表情符号功能。 我已经有一个函数来从其他用户接收字符串。我想要的是 - 如果用户发送的文本包含CharSequence,如“:D”或“:p”,我希望将它们更改为表情符号。我该如何实现这个功能?
我想要一个这样的函数:
public void updateMessage(){
if (receivedMessage.contains(":D")){
receivedMessage.replace(":D",image);
}
messageLog.append(receivedMessage);
}
如果可能,请帮助我。如果还有其他方法,请提及。
答案 0 :(得分:2)
您可以尝试这样
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.
}
答案 1 :(得分:0)
可以使用 SpannableString 轻松实现。这是代码中的示例实现。
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);
}
}