我试图阻止 siteListFragment.kt 中 else 语句中的对话框自动关闭,但尽管我做出了努力,对话框还是会自行关闭。
这是我的代码: siteListFragment.kt
override fun showAddSiteDialog() {
val view: View = LayoutInflater.from(context).inflate(R.layout.dialog_site_add, null)
DialogService.showWithView(
requireContext(),
DialogService.DialogType.INFO,
false,
getString(R.string.add_site),
view,
null,
DialogService.TextWithCallback(getString(R.string.dialog_negative_cancel)){
DialogService.dismiss()
},
DialogService.TextWithCallback(getString(R.string.dialog_positive_add)){
GlobalScope.launch {
val editText = view.findViewById<EditText>(R.id.site_name_add)
val enteredText = editText.text.toString()
withContext(Dispatchers.Main) {
if (siteListPresenter.addSite(enteredText)) {
DialogService.dismiss()
}
//here
else {
editText.error = getString(R.string.network_update_error_empty_name_message)
}
}
}
}
)
}
DialogService.kt
private var dialog: AlertDialog? = null
var builder: AlertDialog.Builder? = null
private fun create(
context: Context,
dialogType: DialogType,
cancelable: Boolean,
title: String,
message: String?
) {
builder = AlertDialog.Builder(context, R.style.CreativePodDialog)
dialog = builder!!.create()
builder!!.apply {
setTitle(title)
setIcon(getIcon(dialogType))
if (message != null && message != "") setMessage(message)
setCancelable(cancelable)
}
}
fun showWithView(
context: Context,
dialogType: DialogType,
cancelable: Boolean,
title: String,
view: View? = null,
negativeButton: TextWithCallback?,
neutralButton: TextWithCallback?,
positiveButton: TextWithCallback?,
) {
create(context, dialogType, cancelable, title, null)
builder!!.apply {
setView(view)
if (positiveButton != null)
setPositiveButton(positiveButton.text) { _, _ ->
positiveButton.callback.invoke()
}
if (negativeButton != null)
setNegativeButton(negativeButton.text) { _, _ ->
negativeButton.callback.invoke()
}
if (neutralButton != null)
setNeutralButton(neutralButton.text) { _, _ ->
neutralButton.callback.invoke()
}
}.show()
}
我尝试将对话框设置为不可取消,这允许您在对话框外部按下而不将其关闭,但不会影响按钮。我还尝试将对话框肯定按钮回调设置为 null,默认为关闭。任何帮助将不胜感激。
AlertDialog
默认情况下有 View.onClickListener
,一旦用户单击肯定或否定按钮,就会自动关闭对话框。
为了防止这种情况发生,您必须自己覆盖监听器。
Button btPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
btPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something here
// dialog won't be dismissed now!
}
});
您可以在 DialogService.TextWithCallback
函数中传递
null回调,使其按预期工作。