34

The user has to enter his mobile number, the mobile number has to be 10 numbers, I used TextWatcher to do that, like this

et_mobile.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        if (et_mobile.getText().toString().length() > 10) {
            et_mobile.setText(et_mobile.getText().toString()
                    .subSequence(0, 10));
            tv_mobileError.setText("Just 10 Number");
        }else{
            tv_mobileError.setText("*");
        }
    }
});

but the problem is when the user enters the 11th number, the cursor of the edittext starts from the beginning of the text, I want it to still at the end, how?

Cœur
  • 32,421
  • 21
  • 173
  • 232
William Kinaan
  • 25,507
  • 20
  • 76
  • 115

3 Answers3

117

You have two options, both should work:

a)

editText.setText("Your text");
editText.setSelection(editText.getText().length());

b)

editText.setText("");    
editText.append("Your text");
jenzz
  • 7,123
  • 6
  • 46
  • 68
6
/**
 * Set pointer to end of text in edittext when user clicks Next on KeyBoard.
 */
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean b) {
        if (b) {
            ((EditText) view).setSelection(((EditText) view).getText().length());
        }
    }
};

mEditFirstName.setOnFocusChangeListener(onFocusChangeListener);
mEditLastName.setOnFocusChangeListener(onFocusChangeListener);

It work good for me!

Infinite Recursion
  • 6,315
  • 28
  • 36
  • 51
Anh Duy
  • 1,004
  • 14
  • 21
0

While jenzz anwser works for the simplest case. It doesn't if your moving the cursor before editing your text because as soon as the second letter is typed it will be moved to the end of the EditText.

Prefer using this solution:

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) 
            {
                ...
                int position = et_mobile.getSelectionStart();
                et_mobile.setText(f(s));
                et_mobile.setSelection(position);
                ...
            }
Gomino
  • 11,353
  • 4
  • 32
  • 43