Android Studio AlertDialog 为对话框添加按钮

  声明,由于时间紧促,笔者只写了在自定义函数内部的代码。 该code提供了为对话框添加按钮的设计方式。
目的:为对话框添加按钮;
作用:为对话框添加按钮;
功能:为对话框添加按钮;

这就意味着:
1. 读者需要知道如何对一个组件添加自定义函数;
2. 明白你需要的组件确实是对话框,如果连对话框都不知道是什么,请移步
3. 知道Button的使用方法
一定要有这个基础,才可以看懂这份代码,有需要的请及时求助搜索引擎。

final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);       
alert.setTitle("your title");
alert.setMessage("your Message");
// Add a PositiveButton;
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    // what if we click the alert;
    public void onClick(DialogInterface dialog, int which) {
        //获取按钮对象
        Button PositiveButton=((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        //现在positiveButton就是一个Button, 处理它就像对待普通的Button一样;
        //具体操作请搜索 Button 的操作;
    });
// Add a NegativeButton;
alert.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // Get Button expressing Negative;
        Button NegativeButton=((AlertDialog)dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
    }
});
alert.show();

你可能感兴趣的:(android-studio)