Search code examples
androidandroidxandroid-preferences

Custom Row Adapter in androidx.preference.ListPreference


Legacy ListPreference in Android comes with:

protected void onPrepareDialogBuilder(android.app.AlertDialog.Builder builder)

That could be use to modify rows in the displayed dialog... see custom row in a listPreference?

This method is not available anymore in the androidx.preference library wondering how to achieve rows customization in the displayed dialog when using androidx.preference support library?


Solution

  • One should override PreferenceFragmentCompat#onDisplayPreferenceDialog(preference: Preference) to display a custom preference dialog :

    override fun onDisplayPreferenceDialog(preference: Preference) {
        if (preference.key == MY_CUSTOM_DIALOG_KEY) {
            if (parentFragmentManager.findFragmentByTag(DIALOG_FRAGMENT_TAG) != null) {
                // already displayed to user
                return
            }
            MyCustomPreferenceDialogFragment.newInstance(preference.key).let {
                it.setTargetFragment(this, 0)
                it.show(parentFragmentManager, DIALOG_FRAGMENT_TAG)
            }
        } else {
            super.onDisplayPreferenceDialog(preference)
        }
    }
    

    To implement your custom preference dialog fragment, you can have a look at implementations from support library :

    • PreferenceDialogFragmentCompat