我正在制作OTP Activity
,并且需要实现删除功能,我具有以下功能,应该在退格按钮的onKey
中触发以下功能。我的想法是,我可以使用getCurrentFocus
知道当前正在填充哪些字段,然后使用requestFocus
之前选择一个字段,但是它似乎不起作用,我为goToNext
设置了另一个功能也可以,所以我很困惑为什么。
public void goToPrevious() {
EditText currentFocus = (EditText) getCurrentFocus();
if (currentFocus == otpOne) {
return;
}
if (currentFocus == otpTwo) {
otpOne.requestFocus();
return;
}
if (currentFocus == otpThree) {
otpTwo.requestFocus();
return;
}
if (currentFocus == otpFour) {
otpThree.requestFocus();
return;
}
}
以下是
goToNext
正常工作的代码。public void goToNext() {
EditText currentFocus = (EditText) getCurrentFocus();
if (currentFocus == otpOne) {
otpTwo.requestFocus();
return;
}
if (currentFocus == otpTwo) {
otpThree.requestFocus();
return;
}
if (currentFocus == otpThree) {
otpFour.requestFocus();
return;
}
if (currentFocus == otpFour) {
return;
}
}
我通过实现onKeyListener来调用goToPrevious,下面是代码
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
EditText currentFocus = (EditText) getCurrentFocus();
Log.i("ENOUGH", "onKey: " + keyCode + " " + event.getAction() + " " + KeyEvent.KEYCODE_DEL);
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DEL: {
currentFocus.setText(null);
goToPrevious();
return false;
}
}
return false;
}
最佳答案
由于某些非常奇怪的原因,我必须通过将getCurrentFocus
的值直接传递到goToPrevious
来修复它,原因是getCurrentFocus
处理程序中的onKey
值不同于goToPrevious
,下面是我最终得到的代码。
public void goToNext(EditText currentFocus) {
if (currentFocus == otpOne) {
otpTwo.requestFocus();
return;
}
if (currentFocus == otpTwo) {
otpThree.requestFocus();
return;
}
if (currentFocus == otpThree) {
otpFour.requestFocus();
return;
}
if (currentFocus == otpFour) {
return;
}
}
public void goToPrevious(EditText currentFocus) {
if (currentFocus == otpOne) {
return;
}
if (currentFocus == otpTwo) {
otpOne.requestFocus();
return;
}
if (currentFocus == otpThree) {
otpTwo.requestFocus();
return;
}
if (currentFocus == otpFour) {
otpThree.requestFocus();
return;
}
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i("ENOUGH", "onKey: " + keyCode + " " + event.getAction() + " " + KeyEvent.KEYCODE_DEL);
if (event.getAction() == KeyEvent.ACTION_DOWN) {
EditText currentFocus = (EditText) getCurrentFocus();
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DEL: {
if (currentFocus.getText().length() > 0) {
currentFocus.setText(null);
} else {
goToPrevious(currentFocus);
EditText focused = (EditText) getCurrentFocus();
focused.setText(null);
}
return false;
}
case KeyEvent.KEYCODE_FORWARD:
return true;
case KeyEvent.KEYCODE_BACK:
return true;
case KeyEvent.KEYCODE_ENTER:
return true;
default: {
currentFocus.setText("");
goToNext(currentFocus);
}
}
}
return false;
}