Android EdittextPreference Hint (android:hint)
I have a preference screen with an EditT开发者_高级运维extPreference. How to set a hint
either in xml like
android:hint
or in code like
setHint(int), setHint(CharSequence hint)
on the EditTextPreference like on an EditText field? I assumed that it´s like on the EditText but i didn´t find anything like this. Thanks.
It's exactly the same to set a hint in XML for an EditTextPreference as it is for an EditText:
android:hint="This is my hint"
This gets passed through to the EditText in the dialog.
This behaviour is confirmed here where it says "It is a subclass of DialogPreference and shows the EditText in a dialog. This EditText can be modified either programmatically via getEditText(), or through XML by setting any EditText attributes on the EditTextPreference."
this is way better, as the accepted answer will not set a hint on the edittext but will set the text to the EditText (long live the small differene).
To really set a hint, use this code:
YourEditTextPreference.getEditText().setHint(R.string.some_hint);
you may also consider adding a summary so the preference will not be displayed with an empty summary
If you are using the AndroidX preference library, you can assign a hint using an OnBindEditTextListener
in your PreferenceFragmentCompat
:
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
PreferenceManager manager = getPreferenceManager();
EditTextPreference textPref = manager.findPreference("myTextPreference");
textPref.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
@Override
public void onBindEditText(@NonNull EditText editText) {
editText.setHint(R.string.hint);
}
});
}
When the input field is empty, the hint should then be displayed as expected.
Kotlin version (AndroidX preference library):
val editTextPref = findPreference<Preference>("prefKey") as EditTextPreference
editTextPref.setOnBindEditTextListener {
it.hint = "My hint"
}
Works in emulator with Android 10 (API level 29).
At the same time, the hint specified in xml does not work:
<EditTextPreference
android:key="prefKey"
android:title="Title"
android:hint="My hint"/>
Use android:summary
to give a brief description of your preference.
You can also set this dynamically using setSummary(CharSequence summary)
.
EDIT: for giving a 'hint' you could use android:defaultValue
.
the way to set "Hints" is to use a summary provider as described in https://developer.android.com/guide/topics/ui/settings/customize-your-settings
the idea is to print a default/hint when the value is null or empty - otherwise, just print out the preference value
val dobPreference: EditTextPreference? = findPreference("key_dob")
dobPreference?.summaryProvider = SummaryProvider<EditTextPreference> { pref ->
if (pref.text.isNullOrBlank()) {
"e.g. Enter your DOB in DDMMYYYY format" // the hint if pref is empty
} else {
pref.text // your preference value if it is not empty.
}
}
精彩评论