在android中将文本转换为表情符号

时间:2014-09-06 10:30:23

标签: android android-edittext

  

在我的应用程序中,我使用此课程将文本更改为表情符号。

public class MainActivity extends Activity {

private static final Factory spannableFactory = Spannable.Factory
        .getInstance();

private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>();

static {
    addPattern(emoticons, ":)", R.drawable.ic_launcher);
    addPattern(emoticons, ":-)", R.drawable.ic_launcher);
    // ...
}

private static void addPattern(Map<Pattern, Integer> map, String smile,
        int resource) {
    map.put(Pattern.compile(Pattern.quote(smile)), resource);
}

public static boolean addSmiles(Context context, Spannable spannable) {
    boolean hasChanges = false;
    for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
        Matcher matcher = entry.getKey().matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(),
                    matcher.end(), ImageSpan.class))
                if (spannable.getSpanStart(span) >= matcher.start()
                        && spannable.getSpanEnd(span) <= matcher.end())
                    spannable.removeSpan(span);
                else {
                    set = false;
                    break;
                }
            if (set) {
                hasChanges = true;
                spannable.setSpan(new ImageSpan(context, entry.getValue()),
                        matcher.start(), matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
    return hasChanges;
}

public static Spannable getSmiledText(Context context, CharSequence text) {
    Spannable spannable = spannableFactory.newSpannable(text);
    addSmiles(context, spannable);
    return spannable;
}

OnClickListener listener1 = new OnClickListener() {
    @Override
    public void onClick(View v) {

        EditText tx = (EditText) findViewById(R.id.editText1);
        tx.getText().insert(tx.getSelectionStart(), getSmiledText(getBaseContext(), ":-)"));

        }};




@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);




    Button btn = (Button) findViewById(R.id.button1);
     btn.setOnClickListener(listener1);


}
  

Q1:我点击了这个按钮并在edittext中显示表情符号。现在我有400个图释,我应该创建400按钮?或者这不是最好的方式?

     

Q2:在app中,当我点击EditText时,SelectionStart()为1或0并从第一行开始输入。如何将selectionstart更改为edittext中第3行的edittext触及的所有用户?

1 个答案:

答案 0 :(得分:4)

使用内置库

https://github.com/ankushsachdeva/emojicon

https://github.com/rockerhieu/emojicon

或创建自定义IME

https://github.com/AnySoftKeyboard/AnySoftKeyboard

如果您在创建自定义软键盘时感到困惑,那么

就会被释放