模拟软键盘删除操作

模拟软键盘删除操作

第一种方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 删除表情和文字
*/
private void deleteEmoji(String str, int selection) {
int start = -1, end = -1;
Matcher matcher = emoji.matcher(str);
while (matcher.find()) { // 遍历最后一个
String key = matcher.group();
start = matcher.start();
end = matcher.start() + key.length();
}
if (start != -1 && end != -1) { // 删除表情
messageContent.getText().delete(start, end);
} else {
if (selection > 0) { // 删除文字
messageContent.getText().delete(selection - 1, selection);
}
}
}
// 表情规则
private Pattern emoji = Pattern.compile(
"[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE
| Pattern.CASE_INSENSITIVE);

第二种方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 模拟删除按键
*/
private void deleteKey() {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DEL);
} catch (Exception ignored) {
}
}
});
}