如下:只需给需要监听返回按键的EditText控件添加该监听即可
editText.setOnKeyListener(new EditKeyListener());
class EditKeyListener implements View.OnKeyListener {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
EditText editText = (EditText) view;
int index = editText.getSelectionStart();
Editable editable = editText.getText();
String editableString = editable.toString();
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (editableString.equals("") || index == 0) {
Toast.makeText(mContext, R.string.exit_setting, Toast.LENGTH_SHORT).show();
return true;
} else {
editable.delete(index - 1, index);
return true;
}
}
}
return false;
}
}
网友评论