零基础学安卓编程

安卓开发入门教程-UI控件_AlertDialog

2020-12-18  本文已影响0人  蓝不蓝编程

什么是AlertDialog

AlertDialog是以提示框形式展示信息的UI控件,.

基础样例

效果图

代码

private fun showDialog() {
    AlertDialog.Builder(this)
        .setTitle("对话框标题")
        .setMessage("对话框内容")
        .setIcon(R.mipmap.ic_launcher)//设置图标
        .setCancelable(true) //设置点击对话框以外区域是否让对话框消失
        //设置确定按钮
        .setPositiveButton("确定") { dialog, _ ->
            Toast.makeText(this, "你点击了确定", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }
        //设置取消按钮
        .setNegativeButton("取消") { dialog, _ ->
            Toast.makeText(this, "你点击了取消", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }
        .create().show()
}

基础样例完整源代码

https://gitee.com/cxyzy1/AlertDialogDemo

常用方法说明

方法名 用途
setTitle 设置标题
setMessage 设置对话框内容
setIcon 设置对话框图标
setCancelable 设置点击对话框以外区域是否让对话框消失,可选值:true:消失,false:不消失
setPositiveButton 设置确定按钮上的文字及点击事件
setNegativeButton 设置取消按钮上的文字及点击事件
上一篇 下一篇

猜你喜欢

热点阅读