安卓:回车键跳转到下一个EditText输入框

3

我有一个包含6个EditText的活动页面,目前可以正常使用,但是需要手动点击每个EditText才能填写内容。

我该如何设置回车键使光标自动跳转到下一个EditText?

我已经尝试过的方法:

1. 我已经为每个EditText设置了OnKeyListener监听器。

switch (v.getId()) {
    case R.id.editText1:
        activity.findViewById(R.id.editText2).requestFocus();
        return true;
    case R.id.editText2:
        activity.findViewById(R.id.editText3).requestFocus();
        return true;
    case R.id.editText3:
        activity.findViewById(R.id.editText4).requestFocus();
        return true;
            .
            .
            .
}

但是,当我点击回车键时,在焦点切换到另一个EditText之前,会在先前的EditText上创建新行。

2。我已经在每个EditText中添加了android:singleLine="true"。它在具有inputType="number"的EditText上无效。


请问您能否尝试添加"android:maxLines="1""吗?根据我的经验,即使其中一个已被"弃用",两者都存在差异。 我认为在这种情况下,您的选项1是正确的选择。 - Tassadar
你也可以尝试使用 "setOnEditorActionListener(...",在 KeyEvent 参数中监听 event.getKeyCode() == KeyEvent.KEYCODE_ENTER 事件,并在此条件为真时返回 true,这应该会阻止 EditText 执行其默认行为。 - Tassadar
Tassadar:设置maxLines="1"会创建一个新行,但edittext不会被调整大小。 - BrunoTS
2个回答

5

0
尝试这段代码:
在OTP屏幕中,我使用了四个编辑框,在此活动中,请按照以下步骤操作。
我正在使用TextWatcher类,就像这样
/* TextWatcher类 */
public class GenericTextWatcher implements TextWatcher {
private View view;

public GenericTextWatcher(View view) {
this.view = view;
}

 @Override
 public void afterTextChanged(Editable editable) {
String text = editable.toString();
switch (view.getId()) {
case R.id.edit_otp1:
if (text.length() == 1)
edit_otp2.requestFocus();
break;
case R.id.edit_otp2:
if (text.length() == 1)
edit_otp3.requestFocus();
break;
case R.id.edit_otp3:
if (text.length() == 1)
edit_otp4.requestFocus();
break;
case R.id.edit_otp4:
break;
   }
 }

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}

@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
}

在编辑文本 OTP 活动中使用 TextWatcher,像这样

/*call textwatcher class*/
    edit_otp1.addTextChangedListener(new GenericTextWatcher(edit_otp1));
    edit_otp2.addTextChangedListener(new GenericTextWatcher(edit_otp2));
    edit_otp3.addTextChangedListener(new GenericTextWatcher(edit_otp3));
    edit_otp4.addTextChangedListener(new GenericTextWatcher(edit_otp4));

对我来说可以运行,请尝试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接