3

Is there anyway to make an EditTextPreference single line? I think that there is no property by default, that can do that. Is necessary to rewrite the object? Anyone have this done?

1
  • Please note: Even if the input field is single line, you still need to check for newlines in the text, if they are not allowed in your data. The reason is, that a multi line text which was copied from elsewhere and then pasted into the single line edit field, will display as one line, but will still contain the newline character. Commented Mar 11, 2020 at 16:27

4 Answers 4

8

Maybe android:singleLine="true" in the layout :

restrict edittext to single line

2
  • 1
    No idea why this answer and the one from CommonsWare was down-voted. This worked perfectly for me (2.3.3). See the Class Overview in the docs. Commented May 2, 2013 at 15:06
  • 5
    Because it doesn't work in the latest version of Android.
    – Mitch
    Commented Jan 14, 2019 at 8:31
6

The following code works now with androidx.preferences >= 1.1.0-alpha01:

        EditTextPreference author_name_pref = findPreference(getString(R.string.author_name_key));
        if (author_name_pref != null) {
            author_name_pref.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
                @Override
                public void onBindEditText(@NonNull EditText editText) {
                    editText.setSingleLine();
                }
            });
        }
3
  • This is indeed the correct answer for androidx. Kotlin style it looks less messy: preferenceScreen.findPreference<EditTextPreference>("the_key")?.setOnBindEditTextListener { it.setSingleLine() }
    – Zap
    Commented Aug 25, 2019 at 17:03
  • 1
    It can be made shorter in java 8 too: EditTextPreference pref = findPreference("the_key"); if (pref != null) { pref.setOnBindEditTextListener(TextView::setSingleLine);}
    – fattire
    Commented Oct 25, 2019 at 1:17
  • and put this code inside onBindPreferences override.
    – user -1
    Commented Jan 2, 2020 at 2:51
2

You can obtain EditText which backs up your EditTextPreference by calling getEditText(). And then do whatever you like with it, like with regular EditText:

EditTextPreference pref=new EditTextPreference(context);
EditText editText=pref.getEditText();
editText.setSingleLine(true);
1

<EditTextPreference> supports the attributes available for <EditText>, and so you should be able to use android:inputMode and such to control the behavior of the EditText widget.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.