作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在首选项屏幕中,我想使用 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 的 MaterialAlertDialogBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61424109/
我是一名优秀的程序员,十分优秀!