自定义一个对话框点击事件接口
import android.content.DialogInterface
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.purui.mobile.utils.LogUtils.d
abstract class CustomDialogInterface(val dialog: DialogInterface?) : View.OnClickListener, DialogInterface.OnClickListener {
override fun onClick(v: View) {
if (null != dialog && dialog is AlertDialog) {
if (v === dialog.getButton(DialogInterface.BUTTON_POSITIVE)) {
onClick(dialog, DialogInterface.BUTTON_POSITIVE)
} else if (v === dialog.getButton(DialogInterface.BUTTON_NEGATIVE)) {
onClick(dialog, DialogInterface.BUTTON_NEGATIVE)
} else if (v === dialog.getButton(DialogInterface.BUTTON_NEUTRAL)) {
onClick(dialog, DialogInterface.BUTTON_NEUTRAL)
} else {
d("CustomDialogInterface", "该 alertdialog 的点击位置不是三大按钮")
}
} else {
d(
"CustomDialogInterface",
"没有调用 setDialog 或 该 dialog 不是 alertdialog 不能通过一般 View 的 setOnclickListener 来代替 DialogInterface.OnClickListener"
)
}
}
override fun onClick(dialog: DialogInterface, which: Int) {}
}
使用方法:将原有的点击事情观察对象给覆盖掉
fun showInputDialog(context:Context, title:String = "提示", positiveButton:DialogButton<String>, negativeButton:DialogButton<Any?>) {
val binding = InputDialogLayoutBinding.inflate(LayoutInflater.from(context))
val alertDialog = AlertDialog.Builder(context)
.setView(binding.root)
.setTitle(title)
.setCancelable(false)
.setPositiveButton(positiveButton.text) { _, _ -> }
.setNegativeButton(negativeButton.text) { _, _ -> }
.create()
alertDialog.show()
val onClickListener = object : CustomDialogInterface(alertDialog) {
override fun onClick(dialog: DialogInterface, which: Int) {
super.onClick(dialog, which)
when (which) {
DialogInterface.BUTTON_POSITIVE-> {
binding.inputContent?.let {
if (it.isBlank()) {
binding.editText.error = "输入不能为空"
return@let
}
positiveButton.clickListener?.invoke(it)
alertDialog.dismiss()
}?:run {
binding.editText.error = "输入不能为空"
}
}
DialogInterface.BUTTON_NEGATIVE-> {
negativeButton.clickListener?.invoke(null)
alertDialog.dismiss()
}
}
}
}
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(onClickListener)
KeyboardUtils.showKeyboard(binding.editText)
}
````