Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setSelection in EditText's onFocusChange

Tags:

android

focus

Normally, when the view is clicked, the text cursor is set near the place you clicked on.
I try to set it always to the end (past the last character), but it does nothing unless the action is delayed.
The following:

new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus) {
            EditText et = (EditText) v;
            et.setSelection(et.getText().length());
        }
    }
});

does not work. Delaying the setSelection part:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        et.setSelection(et.getText().length());
    }
}, 40);

makes it work, but is bad practice.

What better alternatives are there? OnClickListener and OnTouchListener (ACTION_DOWN and ACTION_UP both) don't help, either.

like image 552
kaay Avatar asked Sep 13 '25 10:09

kaay


1 Answers

No need delay. we need to wait setSelection or else automatically called done and execute my setSelection.

new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus) {
            final EditText et = (EditText) v;
            et.post(new Runnable() {
                @Override
                public void run() {
                    et.setSelection(et.getText().length());
                }
            });
        }
    }
});
like image 119
illusionJJ Avatar answered Sep 14 '25 23:09

illusionJJ