Android EditText中插入话题模块的删除处理方法

时间:2022-04-07 23:29:16

在 EditText 中添加话题 或者是 @某人 时

看起来挺简单,实际操作会有很多坑爹的问题

private String mTopic;

//光标保持在话题的末尾
mInputEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { int selectonStart = ((EditText) v).getSelectionStart();
int lastPos = 0;
if (!TextUtils.isEmpty(mCommentName)){
if ((lastPos = mInputEdit.getText().toString().indexOf(mCommentName, lastPos)) != -1) {
if (selectonStart >= lastPos && selectonStart <= (lastPos + mCommentName.length())) {
mInputEdit.setSelection(lastPos + mCommentName.length());
}
}
}else {
if ((lastPos = mInputEdit.getText().toString().indexOf(mTopic, lastPos)) != -1) {
if (selectonStart >= lastPos && selectonStart <= (lastPos + mTopic.length())) {
mInputEdit.setSelection(lastPos + mTopic.length());
}
}
} }
}); //删除话题 或者@某人
mInputEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
//当为删除键并且是按下动作时执行
int selectionStart = mInputEdit.getSelectionStart();
int lastPos = 0;
if (!TextUtils.isEmpty(mCommentName)){
if ((lastPos = mInputEdit.getText().toString().indexOf(mCommentName, lastPos)) != -1) {
if (selectionStart != 0 && selectionStart >= lastPos && selectionStart <= (lastPos + mCommentName.length())) {
String sss = mInputEdit.getText().toString();
mInputEdit.setText(sss.substring(0, lastPos) + sss.substring(lastPos + mCommentName.length()));
mInputEdit.setSelection(lastPos);
return true;
} else {
lastPos += mCommentName.length();
}
}
} else {
if ((lastPos = mInputEdit.getText().toString().indexOf(mTopic, lastPos)) != -1) {
if (selectionStart != 0 && selectionStart >= lastPos && selectionStart <= (lastPos + mTopic.length())) {
String sss = mInputEdit.getText().toString();
mInputEdit.setText(sss.substring(0, lastPos) + sss.substring(lastPos + mTopic.length()));
list.remove(0);
mTopic = "";
mSelectTopic.setText("");
mInputEdit.setSelection(lastPos);
return true;
} else {
lastPos += mTopic.length();
}
}
}
}
return false;
}
});