androix.preference.ListPreference

问题描述

Android中的旧版ListPreference随附:

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

可用于修改显示的对话框中的行... 参见custom row in a listPreference?

androix.preference库中不再提供此方法 想知道在使用androix.preference支持库时如何在显示的对话框中实现行自定义吗?

解决方法

应该覆盖PreferenceFragmentCompat#onDisplayPreferenceDialog(preference: Preference)以显示自定义首选项对话框:

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)
    }
}

要实现您的自定义首选项对话框片段,您可以查看支持库中的实现:

  • PreferenceDialogFragmentCompat