0

我有一个聊天应用程序,我想用表情符号扩展它。

此代码用于在文本中插入笑脸:

   Spanned cs = Html.fromHtml("<img src ='"+ index +"'/>", imageGetter, null);     

   int cursorPosition = content.getSelectionStart();        
   content.getText().insert(cursorPosition, cs);

这很好用。表情符号出现在 textView 的正确位置。

现在我想通过 HTTP 将文本发送到我的服务器。我想存储“:)”而不是图像,因为使用旧应用程序版本的图像无法显示。在新版本中,我在显示文本之前将“:)”转换为图像。有没有办法将图像转换为特定的字符串?

4

1 回答 1

1

如果你想替换你的表情,试试这个:

EditText et = new EditText(this);
et.setTextSize(24);
et.setHint("this view shows \":)\" as an emoticon, try to type \":)\" somewhere");
final Bitmap smile = BitmapFactory.decodeResource(getResources(), R.drawable.emo_im_happy);
final Pattern pattern = Pattern.compile(":\\)");
TextWatcher watcher = new TextWatcher() {
boolean fastReplace = true; 
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //Log.d(TAG, "onTextChanged " + start + " " + before + " " + count);
        if (fastReplace) {
            if (start > 0 && count > 0) {
                String sub = s.subSequence(start - 1, start + 1).toString();
                if (sub.equals(":)")) {
                    Spannable spannable = (Spannable) s;
                    ImageSpan smileSpan = new ImageSpan(smile);
                    spannable.setSpan(smileSpan, start-1, start+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        } else {
            Spannable spannable = (Spannable) s;
            Matcher matcher = pattern.matcher(s);
            while (matcher.find()) {
                int mstart = matcher.start();
                int mend = matcher.end();
                ImageSpan[] spans = spannable.getSpans(mstart, mend, ImageSpan.class);
                Log.d(TAG, "onTextChanged " + mstart + " " + mend + " " + spans.length);
                if (spans.length == 0) {
                    ImageSpan smileSpan = new ImageSpan(smile);
                    spannable.setSpan(smileSpan, mstart, mend, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }
        Log.d(TAG, "onTextChanged " + s);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        Log.d(TAG, "afterTextChanged " + s);
    }
};
et.addTextChangedListener(watcher );

setContentView(et);

在这里,如果fastReplace == true您不必扫描整个文本,但这只是最小的实现:仅当您在输入“:”之后立即输入“)”时才有效,如果fastReplace == false它用笑脸替换每次出现的“:)”但它必须扫描整个文本,因此当文本很大时速度会慢一些

于 2013-06-02T08:22:32.690 回答