gpt4 book ai didi

material-design - 用于 PreferenceFragments 中的 DialogPreferences 的 MaterialAlertDialogBu​​ilder

转载 作者:行者123 更新时间:2023-12-04 10:09:00 25 4
gpt4 key购买 nike

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

据我所知,覆盖它的唯一方法是覆盖: PreferenceFragmentCompat.onDisplayPreferenceDialog() 并从该父类(super class)复制一堆逻辑(在显示对话框片段等方面)。

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

最佳答案

这是我对 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")
}

然后在 PreferenceFragmentCompat子类:
override fun onDisplayPreferenceDialog(preference: Preference) {
if (preference is ListPreference) {
showListPreferenceDialog(preference)
} else {
super.onDisplayPreferenceDialog(preference)
}
}

欢迎反馈!

关于material-design - 用于 PreferenceFragments 中的 DialogPreferences 的 MaterialAlertDialogBu​​ilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61424109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com