Subhash Kumar
Subhash Kumar

Reputation: 53

EditText - Cursor coming to start for every letter when clear text

I set TextWatcher to EditText like below. But when I try to clear text, cursor is coming to start after clearing every letter.

  class MyInputWatcher implements 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) {
        et.removeTextChangedListener(watcher2);
        et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
        et.addTextChangedListener(watcher2);
    }
    @Override
    public void afterTextChanged(Editable s) {

    }
}

Upvotes: 2

Views: 903

Answers (5)

mahesh87
mahesh87

Reputation: 47

Please try like this

editText.setSelection(editText.getText().toString().length());

Upvotes: 1

Ashish
Ashish

Reputation: 132

Do it like this (UPDATED):

class MyInputWatcher implements 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) {
        String temp = s.toString().replaceAll("[^a-zA-Z]", "");
        if (s.toString().length() != temp.length()) {
            et.setText(temp);
            et.setSelection(temp.length());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
}

Upvotes: 1

Matiullah Karimi
Matiullah Karimi

Reputation: 1314

Every time you clear a character it calls onTextChanged() method, as your implementation it get the edittext text and back set to it, so the cursor comes to the starting of the text. Clear et.setText(s.toString().replaceAll("[^[:alpha:]]", "")); and it will be fixed. Or use this et.setSelection(et.getText().toString().length+1);

Upvotes: 0

Suresh Kumar
Suresh Kumar

Reputation: 2034

Set position to your cursor on afterTextChanged() method like this.

class MyInputWatcher implements 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) {
    et.removeTextChangedListener(watcher2);
    et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
    et.addTextChangedListener(watcher2);
}
@Override
public void afterTextChanged(Editable s) {
    et.setSelection(et.getText().toString().length())
}

}

Upvotes: 0

Andrey Alimov
Andrey Alimov

Reputation: 71

Subhash Kumar, you can use method:

et.setSelection(position)

for displaying cursor in need position

Upvotes: 0

Related Questions