就像实现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());
}
}
答案 0 :(得分:0)
有两种方法:
您可以使用以下代码:
final KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
mEdit.onKeyDown(KeyEvent.KEYCODE_DEL, keyEventDown);
SpannableString
并将其重新分配给editText。您只需要在位置=EditText.getSelectionStart();
之前确定它是char还是imagepan因为您的imagespane字符串在“[]”中引用,所以删除“[”和“]”之间的所有字符,包括它们有一些示例代码:
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);
}
}