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

时间:2012-09-17 09:28:55

标签: spannablestring

就像实现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());
    }
}

1 个答案:

答案 0 :(得分:0)

有两种方法:

  1. 简单的方法是按照你的说法调用del按钮功能。
  2. 您可以使用以下代码:

    final KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
    mEdit.onKeyDown(KeyEvent.KEYCODE_DEL, keyEventDown);
    
    1. 此外,您可以处理SpannableString并将其重新分配给editText。您只需要在位置=EditText.getSelectionStart();之前确定它是char还是imagepan因为您的imagespane字符串在“[]”中引用,所以删除“[”和“]”之间的所有字符,包括它们
    2. 有一些示例代码:

      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);
          }
      }