Search code examples
androidandroid-edittextandroid-orientation

How do I move cursor to end of EditText line after an orientation change?


I have an EditText line on a UI screen for a user to enter a sentence. If the the user leaves the cursor in the middle of the sentence and then does an orientation change, I want the cursor to move to the end of the sentence. My understanding was that the OS creates a new Activity and new focus on orientation change so I set up the below code, but to no avail. Please advise.

partial Activity file:

...
cListenerEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if (hasFocus && (cListenerEditText.getText().length() > 0)) {
                cListenerEditText.setSelection(cListenerEditText.getText().length());
             }
         }
    });

Solution

  • Try to do this in onResume instead, checking a boolean field to have it work only on recreation.

    if(!initialized) {
        initialized = true; 
        cListenerEditText.setSelection(cListenerEditText.getText().length());
    }
    

    Edit:

    Sample Activity

    public class MainActivity extends AppCompatActivity {
    
      private EditText cListenerEditText;
      private boolean initialized = false;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cListenerEditText = findViewById(R.id.listenerEditText);
      }
    
      @Override
      protected void onResume() {
        super.onResume();
        if(!initialized) {
          initialized = true;
          cListenerEditText.setSelection(cListenerEditText.getText().length());
        }
      }
    }