PreferenceFragments中的DialogPreferences的MaterialAlertDialogBu​​ilder

时间:2020-04-25 10:15:07

标签: material-design android-preferences android-dialogfragment android-dialog

在首选项屏幕中,我想使用MaterialComponent的对话框(使用MaterialAlertDialogBuilder)代替AppCompat中的AlertDialog。但是,AppCompat的首选项框架使用AlertDialog.Builder进行硬编码。

据我所知,覆盖此内容的唯一方法是覆盖:PreferenceFragmentCompat.onDisplayPreferenceDialog()并从该超类复制一堆逻辑(就显示对话框片段等而言)。

这是正确的方法还是有更好的方法?

2 个答案:

答案 0 :(得分:1)

这是我对getPostResponse的解决方案:

Post

,然后在ListPreference子类中:

class MaterialListPreferenceDialogFragment : ListPreferenceDialogFragmentCompat() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val context: Context? = activity
        mWhichButtonClicked = DialogInterface.BUTTON_NEGATIVE
        val builder = MaterialAlertDialogBuilder(requireActivity())
            .setTitle(preference.dialogTitle)
            .setIcon(preference.dialogIcon)
            .setPositiveButton(preference.positiveButtonText, this)
            .setNegativeButton(preference.negativeButtonText, this)
        val contentView = onCreateDialogView(context)
        if (contentView != null) {
            onBindDialogView(contentView)
            builder.setView(contentView)
        } else {
            builder.setMessage(preference.dialogMessage)
        }
        onPrepareDialogBuilder(builder)

        val dialog = builder.create()
        //if (needInputMethod()) {
        //    requestInputMethod(dialog)
        //}
        return dialog
    }

    /* Override the methods that access mWhichButtonClicked (because we cannot set it properly here) */

    /** Which button was clicked.  */
    private var mWhichButtonClicked = 0

    override fun onClick(dialog: DialogInterface?, which: Int) {
        mWhichButtonClicked = which
    }

    override fun onDismiss(dialog: DialogInterface) {
        onDialogClosedWasCalledFromOnDismiss = true
        super.onDismiss(dialog)
    }

    private var onDialogClosedWasCalledFromOnDismiss = false

    override fun onDialogClosed(positiveResult: Boolean) {
        if (onDialogClosedWasCalledFromOnDismiss) {
            onDialogClosedWasCalledFromOnDismiss = false
            // this means the positiveResult needs to be calculated from our mWhichButtonClicked
            super.onDialogClosed(mWhichButtonClicked == DialogInterface.BUTTON_POSITIVE)
        } else {
            super.onDialogClosed(positiveResult)
        }
    }
}

fun PreferenceFragmentCompat.showListPreferenceDialog(preference: ListPreference) {
    val dialogFragment = MaterialListPreferenceDialogFragment().apply {
        arguments = Bundle(1).apply {
            putString("key", preference.key)
        }
    }
    dialogFragment.setTargetFragment(this, 0)
    dialogFragment.show(parentFragmentManager, "androidx.preference.PreferenceFragment.DIALOG")
}

欢迎反馈!

答案 1 :(得分:1)

对我来说,将其添加到主题中会使首选项对话框出现在材质设计中:

sudo apt autoremove && sudo apt autoclean

至少已适应字体和颜色,但是对话框的角仍然不如MaterialAlertDialogBu​​ilder的圆角