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

24,117

Solution 1

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);

Solution 2

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.

Solution 3

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());
      }

Solution 4

Above solution is not working.

Here I give you new solution for set focus to right of text in edittext for android. And its working fine.

My code is:

    EditText edt_ans = (EditText)findViewById(R.id.edt_answer);

    edt_ans.addTextChangedListener(new TextWatcher() 
    { 
          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) 
          {
               // TODO Auto-generated method stub
                edt_ans.setSelection(edt_ans.getText().length());
          }
          @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

          }
   });

Happy Coding....:)

Share:
24,117
Vinod
Author by

Vinod

Updated on July 31, 2022

Comments

  • Vinod
    Vinod almost 2 years

    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.