我有一个" edittext"在我的应用程序中,我想在软键盘上按下某些字符时执行操作。 我已尝试过各种方式以及stackOverflow的建议方式,但不会检测到a / A,b / B等字符。但是输入和Del。 阅读加载后,显然我必须覆盖edittext类,根据这里的一个例子,所以我已经做到了。 我在这里重写方法:
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_A) {
ZanyEditText.this.setRandomBackgroundColor();
return false;
}
return super.sendKeyEvent(event);
}
我也试过覆盖标准的edittext onKeyListener:
txtSMS.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL) {
// this is for backspace
Toast.makeText(getApplicationContext(), "Del was pressed", Toast.LENGTH_SHORT).show();
}
if (keyCode == KeyEvent.KEYCODE_A) {
// this is for backspace
Toast.makeText(getApplicationContext(), "A was pressed", Toast.LENGTH_SHORT).show();
}
return false;
}
然而,在这两种情况下,Del都被检测到了。为什么我不能检测字母表中的字符?它们出现在文本框中......
由于
答案 0 :(得分:0)
我有类似的问题,你需要使用TextWatcher,然后检测输入的最后一个字符是什么(使用' subSequence')。按下了确定删除的使用逻辑或输入了a,希望这有帮助
见下面的代码:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
//this is the method that detects the last entry below
String c = s.subSequence(before, before + 1).toString();
//check for delete
if (before < s.length()) {
String c = s.subSequence(before, before + 1).toString();
//see if a was entererd
if (c == a) {
//a entered
}
} else {
//delete pressed
}
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
});