使用 EditText 连续输入 OTP

Sud*_*dip 0 android android-layout android-input-method android-edittext

这里是 4EditText用于输入数字密码。我希望它是这样的,如果第一个EditText由 1 个数字填充,那么焦点应该转到下一个EditText并且也应该以相反的方式工作。这样用户就可以继续从最左边输入密码,也可以从最右边以同样的方式擦除。

有人可以建议什么是最好的方法吗?

目前看起来像这样

Ben*_*sal 5

您无法单独使用 addTextChangedListener 完成它。您可能必须同时设置 onKeyListener 。这是给你的代码:

//6 EditTexts are otpEt[0], otpEt[1],...otpEt[5]
private EditText[] otpEt = new EditText[6];
    otpEt[0] = (EditText) findViewById(R.id.otpEt1);
    otpEt[1] = (EditText) findViewById(R.id.otpEt2);
    otpEt[2] = (EditText) findViewById(R.id.otpEt3);
    otpEt[3] = (EditText) findViewById(R.id.otpEt4);
    otpEt[4] = (EditText) findViewById(R.id.otpEt5);
    otpEt[5] = (EditText) findViewById(R.id.otpEt6);

setOtpEditTextHandler();

private void setOtpEditTextHandler () { //This is the function to be called
    for (int i = 0;i < 6;i++) { //Its designed for 6 digit OTP
        final int iVal = i;

        otpEt[iVal].addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(iVal == 5 && !otpEt[iVal].getText().toString().isEmpty()) {
                    otpEt[iVal].clearFocus(); //Clears focus when you have entered the last digit of the OTP.
                } else if (!otpEt[iVal].getText().toString().isEmpty()) {
                    otpEt[iVal+1].requestFocus(); //focuses on the next edittext after a digit is entered.
                }
            }
        });

        otpEt[iVal].setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() != KeyEvent.ACTION_DOWN) {
                    return false; //Dont get confused by this, it is because onKeyListener is called twice and this condition is to avoid it.
                }
                if(keyCode == KeyEvent.KEYCODE_DEL && 
otpEt[iVal].getText().toString().isEmpty() && iVal != 0) {
//this condition is to handel the delete input by users.
                    otpEt[iVal-1].setText("");//Deletes the digit of OTP
                    otpEt[iVal-1].requestFocus();//and sets the focus on previous digit
                }
                return false;
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您觉得这段代码很困难,只需将其粘贴到您的项目中并尝试重新排列。您将能够轻松获得