Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditTextPreference and default cursor position

This is mostly a pet peeve of mine, but it annoys me to no end that the default behavior or EditTextPreferences is to put the cursor at the beginning of the string. This makes NO sense at all to me. In almost any other interface known to man (fine, ME), focusing on a textfield automatically sends the cursor to the END.

So. Is there an (easy) way to override this? I know I can extend from EditTextPreference and call setSelection() manually, but this seems like a really complicated solution for such a simple problem.

like image 285
dmon Avatar asked May 06 '11 19:05

dmon


3 Answers

Another angle on this: I just wind up setting 'selectAllOnFocus' to true either in the XML definition, or programmatically on the object.

It basically accomplished what I wanted: to have the end user be able to replace the contents immediately.

like image 168
TobyD Avatar answered Nov 06 '22 10:11

TobyD


Similar to lukeuser's solution, you can define the OnPreferenceClickListener inline or as a class variable:

final OnPreferenceClickListener _moveCursorToEndClickListener =
    new OnPreferenceClickListener()
    {
        @Override
        public boolean onPreferenceClick(Preference preference)
        {
            EditTextPreference editPref = (EditTextPreference)preference;
            editPref.getEditText().setSelection( editPref.getText().length() );
            return true;
        }
    };

[...]

EditTextPreference myPref = (EditTextPreference)findPreference( "MyPref" );
myPref.setOnPreferenceClickListener( _moveCursorToEndClickListener );

Or

EditTextPreference myPref = (EditTextPreference)findPreference( "MyPref" );
myPref.setOnPreferenceClickListener(
    new OnPreferenceClickListener()
    {
        @Override
        public boolean onPreferenceClick(Preference preference)
        {
            EditTextPreference editPref = (EditTextPreference)preference;
            editPref.getEditText().setSelection( editPref.getText().length() );
            return true;
        }
    } );
like image 7
Toland Hon Avatar answered Nov 06 '22 09:11

Toland Hon


I ended up extending EditTextPreference and overriding the showDialog method:

  @Override
  protected void showDialog(Bundle state) {
    super.showDialog(state);
    Handler delayedRun = new Handler();
    delayedRun.post(new Runnable() {
      @Override
      public void run() {
        EditText textBox = getEditText();
        textBox.setSelection(textBox.getText().length());
      }
    });
  }
like image 3
dmon Avatar answered Nov 06 '22 10:11

dmon