app开发者平台在数字化时代的重要性与发展趋势解析
943
2022-09-10
【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
champer_form.xml
styles.xml
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~