【Android,Kotlin】自定义弹框的简单写法Demo

网友投稿 963 2022-09-10

【Android,Kotlin】自定义弹框的简单写法Demo

【Android,Kotlin】自定义弹框的简单写法Demo

自定义弹框的简单写法Demo

效果

源码

​​Koltin​​ CustomDialog

package com.sq.module.widgetimport android.app.Dialogimport android.content.Contextimport android.content.DialogInterfaceimport android.view.LayoutInflaterimport android.view.Viewimport android.widget.Buttonimport android.widget.LinearLayoutimport android.widget.TextViewimport com.sq.module.R/** * @ClassName ExitDialog * @Description TODO * @Author Kolin Zhao * @Date 2021/6/3 20:45 * @Version 1.0 */class CustomDialog : Dialog { constructor(context: Context?) : super(context!!) constructor(context: Context?, theme: Int) : super(context!!, theme) class Builder(private val context: Context) { var content: String? = null private var positiveButtonClickListener: DialogInterface.OnClickListener? = null private var negativeButtonClickListener: DialogInterface.OnClickListener? = null fun setContent(content: String): Builder { this.content = content return this } fun setPositiveButton(listener: DialogInterface.OnClickListener): Builder { this.positiveButtonClickListener = listener return this } fun setNegativeButton(listener: DialogInterface.OnClickListener): Builder { this.negativeButtonClickListener = listener return this } fun create(): CustomDialog { val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater //为自定义弹框设置主题 val customDialog = CustomDialog(context, R.style.CustomDialog) val view = layoutInflater.inflate(R.layout.dialog_exit, null) customDialog.addContentView(view, LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT )) //设置弹框内容 content?.let { (view.findViewById(R.id.dialog_content) as TextView).text = it } //设置弹框按钮 positiveButtonClickListener?.let { (view.findViewById(R.id.dialog_sure) as Button).setOnClickListener { positiveButtonClickListener!!.onClick(customDialog, DialogInterface.BUTTON_POSITIVE) } } ?: run { (view.findViewById(R.id.dialog_sure) as Button).visibility = View.GONE } negativeButtonClickListener?.let { (view.findViewById(R.id.dialog_cancel) as Button).setOnClickListener { negativeButtonClickListener!!.onClick(customDialog, DialogInterface.BUTTON_NEGATIVE) } } ?: run { (view.findViewById(R.id.dialog_cancel) as Button).visibility = View.GONE } customDialog.setContentView(view) return customDialog } }}

调用

val builder = CustomDialog.Builder(this)builder.setPositiveButton(DialogInterface.OnClickListener { dialogInterface, _ -> dialogInterface.dismiss() //具体逻辑})builder.setNegativeButton(DialogInterface.OnClickListener { dialogInterface, _ -> dialogInterface.dismiss() //具体逻辑})builder.create().show()

​​Layout​​ dialog_exit.xml

上一篇:AD RPC SMB端口 Port 组策略编辑器打不开
下一篇:文件上传(文件上传绕过)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~