AlertDialog 弹窗

Window
 DecorView
  Container
   LinearLayout
    TextView
    Button

//设置decorView为透明色
alertDialog.window!!.decorView.setBackgroundColor(Color.TRANSPARENT)
//设置弹窗显示的位置(不设置默认是中间)
alertDialog.window!!.setGravity(Gravity.BOTTOM)

弹窗是要显示在window上面的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
val alertDialog = AlertDialog
.Builder(this)
.setTitle("请选择用户")
.setMessage("这里需要你选择对应的登录用户")
//内部类形式
.setNegativeButton("取消",object :OnClickListener{
override fun onClick(dialog: DialogInterface?, which: Int) {
Toast.makeText(this@MainActivity,"$which 被点击了",Toast.LENGTH_LONG).show()
}
})
//lambda表达式形式
.setPositiveButton("确定"){dialog,which ->
Toast.makeText(this,"$which 被点击了",Toast.LENGTH_LONG).show()
}
.create()
alertDialog.show() //显示

默认例子.png

setView()自定义
新增layout资源文件,设计弹窗视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
val view = layoutInflater.inflate(R.layout.alert_ok_layout,null,false)//解析(如果只是将画面弹出而不需要做任何操作即可只是将资源文件传入,如果需要交互则需要解析资源文件)
val alertDialog = AlertDialog
.Builder(this)
.setView(view)
.create()

//对自定义视图中的控件做操作(处理界面的事件)
val btnView = view.findViewById<Button>(R.id.button)
btnView.setOnClickListener {
alertDialog.dismiss()
//...其他操作
}
alertDialog.window!!.decorView.setBackgroundColor(Color.TRANSPARENT)
alertDialog.show() //显示

自定义.png

封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class NameDialog: DialogFragment() { //也可以继承自BottomSheetDialogFragment()实现从底部弹出
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view = layoutInflater.inflate(R.layout.alert_ok_layout,null,false)
val alertDialog = AlertDialog
.Builder(requireContext())
.setView(view)
.create()

view.findViewById<Button>(R.id.button).setOnClickListener {
dismiss()
}

alertDialog.window!!.decorView.setBackgroundColor(Color.TRANSPARENT)
alertDialog.window!!.setGravity(Gravity.BOTTOM)

return alertDialog
}
}


//在需要的地方进行调用
NameDialog().show(supportFragmentManager,"name")


Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2023-2025 Annie
  • Visitors: | Views:

嘿嘿 请我吃小蛋糕吧~

支付宝
微信