Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus to right of text in EditText for android?

In my application when users click or touch on the Edit Text view the focus is sometimes set to the beginning. For example if the existing text is "Hi". Users wants to click on it and change it to "H1 How are you?" by adding the text "How are you?". But since the focus is in the beginning, it becomes "How are you?Hi". So I always want to set to focus to the right most of the text when selected. How do I do this. Please let me know with some sample if possible. Thank you for your time and help.

like image 536
Vinod Avatar asked Jun 30 '11 00:06

Vinod


People also ask

How do I change the focus to next text in Android?

Use android:nextFocusDown="next_EditText_id" Show activity on this post. Show activity on this post. The solution coding is OK, Below codes indicate that auto move to next Edit Text and auto move to previous Edit Text.

How do I change focus on text?

Show activity on this post. I have an EditText-Field and set an OnFocusChangeListener for it. When it has lost focus, a method is called, which checks the value of the EditText with one in the database. If the return-value of the method is true, a toast is shown and the focus should get back on the EditText again.

What does focusable mean Android?

Focusable means that it can gain the focus from an input device like a keyboard. Input devices like keyboards cannot decide which view to send its input events to based on the inputs itself, so they send them to the view that has focus.

How do I know if EditText has focus?

You can use View. OnFocusChangeListener to detect if any view (edittext) gained or lost focus. This goes in your activity or fragment or wherever you have the EditTexts.


3 Answers

You can explicitly put caret to last position in text:

EditText editText = (EditText) findViewById(R.id.textId);
int pos = editText.getText().length();
editText.setSelection(pos);
like image 183
inazaruk Avatar answered Oct 18 '22 08:10

inazaruk


Something more especific about that you ask, you can use the next code:

EditText editText = (EditText) findViewById(R.id.textId);    
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus){
            editText.setSelection(editText.getText().length());
        }
    }
});

the method setOnFocusChangeLister() is used for detect when the editText receive the focus.

like image 45
Maria Mercedes Wyss Alvarez Avatar answered Oct 18 '22 08:10

Maria Mercedes Wyss Alvarez


setSelection wasn't working for me, but this works like a charm. Works on afterTextChanged as well.

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) 
      {
          edittext.requestFocus(edittext.getText().length());
      }
like image 27
Unu Avatar answered Oct 18 '22 09:10

Unu