Android开发:AlertDialog的使用

AlertDialog可以在当前界面上弹出一个对象框,此对话框置于所有界面上面,且可以屏蔽他们的交互能力。一般用于一些重要的提示内容。
AlertDialog不用在布局文件中声明,而是通过代码文件中的构造器来生成并显示。
下面的代码展示了AlertDialog的基本使用方法。
总结一下,使用AlertDialog的基本步骤。

  1. 创建一个AlertDialog.Builder()对象。
  2. 设置title和message等。
  3. 设置按钮的监听器。
  4. 调用show()方法显示之。

修改按钮颜色的方法
调用AlertDialog的getButton就可以得到一个Button对象,然后就可以设置啦。值得注意的是,设置方法之前应该调用show()方法,因为次方法才能返回AlertDialog对象。

package com.example.alertdialog

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn.setOnClickListener {
            createAlertDialog()
        }
    }

    //显示一个对话框
    public fun createAlertDialog() {
        //构建一个对话框
        val builder = AlertDialog.Builder(this)
        //设置title
        builder.setTitle("这是一个对话框")
        //设置对话框的内容
        builder.setMessage("这是对话框的内容")

        //设置正面按钮
        builder.setPositiveButton("确定") { dialogInterface, i ->
            Toast.makeText(this, "你点击了确定按钮", Toast.LENGTH_SHORT).show()
        }

        //设置反面按钮
        builder.setNegativeButton("取消") { dialogInterface, i ->
            Toast.makeText(this, "你点击了取消按钮", Toast.LENGTH_SHORT).show()
        }

        //设置中立按钮
        builder.setNeutralButton("中立") { dialogInterface, i ->
            Toast.makeText(this, "你点击了中立按钮", Toast.LENGTH_SHORT).show()
        }

        //将对话框显示出来
        //show()函数返回一个AlertDialog对象
        val dialog = builder.show()

        //设置按钮颜色:getButton返回一个Button对象,因此可以直接设置颜色了
        //类似的,还可以设置其他样式,比如字体等
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED)
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.GREEN)
        dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(Color.YELLOW)


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值