I have a preference screen which uses the AndroidX Preference API and I'm using a MultiSelectListPreference which gets its entries populated dynamically.
Due to that, the entries array can be empty, and in this situation I want to show a text like "No items found". Currently I tried setting the placeholder text as an entry, and although this technically works it allows the user to select this entry (the checkbox still appears).
Any ideas on how to show a placeholder text, but making sure the checkbox does not appear?
Thank you
You can initially set the MultiSelectListPreference
as disabled in your preference XML file, then enable it programmatically using Preference#setEnabled
once the values are set.
See below for an example:
pref_todo.xml
:
<androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- ... -->
<MultiSelectListPreference
app:enabled="false"
app:title="@string/pref_weekly_summary_title"
app:summary="@string/pref_weekly_summary_summary"
app:key="pref_weekly_summary" />
<!-- ... -->
</androidx.preference.PreferenceScreen>
Your preference fragment's code (Java):
import androidx.preference.PreferenceFragment;
import androidx.preference.MultiSelectListPreference;
// ...
public class TodoPreferenceFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootkey) {
setPreferencesFromResource(R.xml.pref_todo, rootKey);
// Cast from a Preference to a MultiSelectListPreference
MultiSelectListPreference weeklySummaryListPref = (MultiSelectListPreference) findPreference("pref_weekly_summary");
// Set the entries
weeklySummaryListPref.setEntries(new CharSequence[]{"Todos progress", "Todos completed"});
weeklySummaryListPref.setEntryValues(new CharSequence[]{"todos_progress", "todos_completed"});
// Lastly, reenable the preference
weeklySummaryListPref.setEnabled(true);
}
}
Your preference fragment's code (Kotlin w/ Preference KTX):
import androidx.preference.PreferenceFragment
import androidx.preference.MultiSelectListPreference
// ...
class TodoPreferenceFragment: PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.pref_todo, rootKey)
// Cast from a Preference to a MultiSelectListPreference
// Note: This syntax is only supported on AndroidX Preference versions 1.1.0-alpha02 and up
val weeklySummaryListPref = findPreference<MultiSelectListPreference>("pref_weekly_summary")
// Set the entries
weeklySummaryListPref.entries = arrayOf("Todos progress", "Todos completed")
weeklySummaryListPref.entryValues = arrayOf("todos_progress", "todos_completed")
// Lastly, reenable the preference
weeklySummaryListPref.enabled = true
}
}