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?
Asked
Active
Viewed 2,813 times
3
-
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. – user2808624 Mar 11 '20 at 16:27
4 Answers
8
Maybe android:singleLine="true"
in the layout :
-
1No 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](http://developer.android.com/reference/android/preference/EditTextPreference.html). – William Carter May 02 '13 at 15:06
-
5
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();
}
});
}

lumag
- 61
- 1
- 3
-
This is indeed the correct answer for androidx. Kotlin style it looks less messy: `preferenceScreen.findPreference
("the_key")?.setOnBindEditTextListener { it.setSingleLine() }` – Zap Aug 25 '19 at 17:03 -
1It can be made shorter in java 8 too: `EditTextPreference pref = findPreference("the_key"); if (pref != null) { pref.setOnBindEditTextListener(TextView::setSingleLine);}` – fattire Oct 25 '19 at 01:17
-
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);

Andrii Chernenko
- 9,873
- 7
- 71
- 89
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.

CommonsWare
- 986,068
- 189
- 2,389
- 2,491