Edit text for OTP with Each letter in separate positions

后端 未结 19 1000
别跟我提以往
别跟我提以往 2020-12-13 00:25

I\'m working on a application which asks for OTP when user want to reset his password for which I need a text like the one in attached Image... What I thought to proceed wi

19条回答
  •  执笔经年
    2020-12-13 01:02

    You can try this, by making TextWatcher more Generic, so its easy to use and understand

    Use below class:

    public class GenericTextWatcher implements TextWatcher
        {
            private View view;
            private GenericTextWatcher(View view) 
            {
                this.view = view;
            }
    
            @Override
            public void afterTextChanged(Editable editable) {
                // TODO Auto-generated method stub
                String text = editable.toString();
                switch(view.getId())
                {
    
                case R.id.editText1:
                    if(text.length()==1)
                        et2.requestFocus(); 
                    break;
                case R.id.editText2:
                    if(text.length()==1)
                        et3.requestFocus();
                    else if(text.length()==0)
                        et1.requestFocus();  
                    break;
                case R.id.editText3:
                    if(text.length()==1)
                        et4.requestFocus();
                    else if(text.length()==0)
                        et2.requestFocus();
                    break;
                case R.id.editText4:
                    if(text.length()==0)
                        et3.requestFocus();
                    break;
                }
            }
    
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
            }
    
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
            }
        }
    

    How to use above class

    et1.addTextChangedListener(new GenericTextWatcher(et1));
    et2.addTextChangedListener(new GenericTextWatcher(et2));
    et3.addTextChangedListener(new GenericTextWatcher(et3));
    et4.addTextChangedListener(new GenericTextWatcher(et4));
    

    Here et1,et2,et3 and et4 are your EditTexts, I know its bad naming convention as per Java Standard, but you can replace it with yours.

    P.S You can find the xml design for this here GitHub some other, sample design xml for reference

提交回复
热议问题