0

就像实现del按钮功能一样

如何通过 EditText.getSelectionStart() 删除 EditText 中的 SpannableString

private void enterExpression(String imageFile) {
    try {
        Field field = R.drawable.class.getDeclaredField(imageFile);
        int resourceId = Integer.parseInt(field.get(null).toString());
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                resourceId);
        ImageSpan imageSpan = new ImageSpan(bitmap);

        SpannableString spannableString = new SpannableString("[/"
                + imageFile + "]");
        spannableString.setSpan(imageSpan, 0, spannableString.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        sendContentEdt.append(spannableString);
    } catch (Exception e) {
        LogUtils.e(TAG, "enterExpressionException:" + e.getMessage());
    }
}
4

1 回答 1

0

有两种方法:

  1. 简单的方法是按照您所说的调用 del 按钮功能。

您可以使用如下代码:

final KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
mEdit.onKeyDown(KeyEvent.KEYCODE_DEL, keyEventDown);
  1. 此外,您可以处理并将其SpannableString重新分配给editText。您只需要在位置之前确定它是字符还是图像跨度=EditText.getSelectionStart();由于您的图像窗格字符串在“[]”中引用,因此您删除了“[”和“]”之间的所有字符,包括它们。

有一些示例代码:

StringBuffer localStringBuffer = new StringBuffer(mEdit.getText().toString());
int i,j;
String result;
if (localStringBuffer.length() > 0) {
    i = cursor;
    if (i != 0) {
        char ch = localStringBuffer.charAt(i - 1);
        if (localStringBuffer.charAt(i - 1) != ']') {
            result = localStringBuffer.toString().substring(0, i - 1) + localStringBuffer.toString().substring(i);
            j = i-1;
        }else{
            j =localStringBuffer.substring(0, i - 1).lastIndexOf("[");
            if(j==-1) j =i;
            result = localStringBuffer.toString().substring(0, j) + localStringBuffer.toString().substring(i);
        }
        mEdit.setText(addSmileySpansFromCode(result));
        mEdit.setSelection(j);
    }
}
于 2012-09-28T09:30:01.053 回答