AlertDialog可以在当前界面上弹出一个对象框,此对话框置于所有界面上面,且可以屏蔽他们的交互能力。一般用于一些重要的提示内容。
AlertDialog不用在布局文件中声明,而是通过代码文件中的构造器来生成并显示。
下面的代码展示了AlertDialog的基本使用方法。
总结一下,使用AlertDialog的基本步骤。
- 创建一个
AlertDialog.Builder()
对象。 - 设置title和message等。
- 设置按钮的监听器。
- 调用
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) } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/894439.html