当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发:AlertDialog的使用

Android开发:AlertDialog的使用

2020年08月10日  | 移动技术网移动技术  | 我要评论

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)


    }
}

本文地址:https://blog.csdn.net/weixin_42708161/article/details/107898517

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网