核心思想就是通过Dialog的构造函数来创建Dialog,然后给Dialog设置自定义布局
fun showAlertDialog(context: Context, title: String, message: CharSequence, positive: String, negative: String, cmListener: ConfirmListener?, clListener: CancelListener?): Dialog {
val dialog = Dialog(context, R.style.KfDialog)
val contentView = LayoutInflater.from(context).inflate(R.layout.kf_dialog, null)
val contentTv = contentView.findViewById<TextView>(R.id.dialog_content)
val titleTv = contentView.findViewById<TextView>(R.id.dialog_title)
val negativeTv = contentView.findViewById<TextView>(R.id.dialog_negative)
val positiveTv = contentView.findViewById<TextView>(R.id.dialog_positive)
contentTv.text = message
titleTv.text = title
negativeTv.text = negative
positiveTv.text = positive
negativeTv.setOnClickListener {
clListener?.onCancel()
dialog.dismiss()
}
positiveTv.setOnClickListener {
cmListener?.onConfirm()
dialog.dismiss()
}
dialog.setCancelable(false)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(contentView)
dialog.show()
return dialog
}
其中style是Dialog弹窗的样式,在styles.xml里面定义,比如:
<style name = "KfDialog" parent = "Theme.AppCompat.Light.Dialog.Alert" >
<item name = "android:textSize" >17sp</item >
<item name = "android:textColor" >#000</item >
</style >