1

I have an activity in which I get from the user credit card's serial number. It contains four editTexts - each one for 4 digits. I've used an array for the editTexts -

EditText[] editSerial = new EditText[4];

and I've restricted the input's length in each editText with

android:maxLength="4"

I want the focus to move to the next editText once the user have entered 4 digits in the current one. I've seen this answer - How to automatically move to the next edit text in android:

et1.addTextChangedListener(new TextWatcher() {

public void onTextChanged(CharSequence s, int start,int before, int count) 
{
    // TODO Auto-generated method stub
    if(et1.getText().toString().length()==size)     //size as per your requirement
    {
        et2.requestFocus();
    }
}

Is there any BETTER solution than repeat this code 3 times?

Community
  • 1
  • 1
TDG
  • 5,909
  • 3
  • 30
  • 51
  • You can use one editext, this [link](http://stackoverflow.com/questions/5947674/custom-format-edit-text-input-android-to-accept-credit-card-number) should help – Piotr Golinski Apr 24 '15 at 08:35

1 Answers1

1

Kind of. You need a TextWatcher on each one but you can extract it as a proper class so that you can pass in parameters indicating the View to focus on next.

Then it'll be like

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

The class:

private static class FocusSwitchingTextWatcher implements TextWatcher {

    private final View nextViewToFocus;

    TextWatcher(View nextViewToFocus) {
        this.nextViewToFocus = nextViewToFocus;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length > size) {
            nextViewToFocus.requestFocus();
        }
    }

    ... // the other textwatcher methods 

}
ataulm
  • 15,195
  • 7
  • 50
  • 92
  • *I'd double check the actual TextWatcher method to override though, I don't remember what each of the params actually are – ataulm Apr 24 '15 at 08:54
  • 1
    Thanks, only one minor thing - the class should IMPLEMENT the TextWatcher, not to EXTEND it. I cannot vote up this answer, because my reputation is too low... – TDG Apr 24 '15 at 09:42