et_content.setOnKeyListener(new EditKeyListener());
private class EditKeyListener implements View.OnKeyListener{ @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) { //当为删除键并且是按下动作时执行 int selectionStart = et_content.getSelectionStart(); int lastPos = 0; int l = 0; for (int i = 0; i < be.size(); i++) { //循环遍历整个输入框的所有字符 if ((lastPos = et_content.getText().toString().indexOf("@"+be.get(i).getRealName(), lastPos)) != -1) { if (selectionStart != 0 && selectionStart >= lastPos && selectionStart <= (lastPos + ("@"+be.get(i).getRealName()).length())) { String sss = et_content.getText().toString(); String s1 = sss.substring(0, lastPos); String s2 = sss.substring(lastPos +("@"+ be.get(i).getRealName()).length()); String s3 = s1+s2; be.remove(i); //删除对应实体 et_content.setText(s3); for (int j = 0; j <be.size() ; j++) { if(s3.contains("@"+ be.get(j).getRealName())){ SpannableString ss = new SpannableString(s3); ss.setSpan(new ForegroundColorSpan(AskAcktivity.this.getResources() .getColor(R.color.title_bar_bg)), 0, l+("@"+ be.get(j).getRealName()).length()+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); et_content.setText(ss); //字符串替换,删掉符合条件的字符串 l += ("@"+ be.get(j).getRealName()).length(); }else{ et_content.setText(s3); } } et_content.setMovementMethod(LinkMovementMethod.getInstance()); et_content.setSelection(lastPos); //设置光标位置 return true; } } else { lastPos += ("@" + be.get(i).getRealName()).length(); } } } return false; } }