Android开发学习:[6]AlertDialog

2025-11-21 08:13:50

1、首先我们在界面布局上面布局四个按钮

Android开发学习:[6]AlertDialog

2、然后我们在代码中关联这四个按钮:

Button button3=(Button)findViewById(R.id.button3);

        Button button4=(Button)findViewById(R.id.button4);

        Button button5=(Button)findViewById(R.id.button5);

        Button button6=(Button)findViewById(R.id.button6);

Android开发学习:[6]AlertDialog

3、然后我们敲入AlterDialog代码:

//显示带中立,取消,确定的提示框

        button3.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this).create();

                //alertDialog.setIcon(R.drawable.desert);

                alertDialog.setTitle("System Information:");

                alertDialog.setMessage("Dialog with cancel confirm and neutral button!");

                //添加取消按钮

                alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"Cancel",new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        Toast.makeText(MainActivity.this,"You clicked the Cancel Button",Toast.LENGTH_LONG).show();

                    }

                });

                //添加确定按钮

                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,"Confirm",new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        Toast.makeText(MainActivity.this,"You clicked the Confirm Button",Toast.LENGTH_LONG).show();

                    }

                });

                //添加中立按钮

                alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,"neutral",new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        Toast.makeText(MainActivity.this,"You clicked the neutral Button",Toast.LENGTH_LONG).show();

                    }

                });

                alertDialog.show();

            }

        });

图片请注意看行号

Android开发学习:[6]AlertDialog

Android开发学习:[6]AlertDialog

4、现在我们点击运行按钮,运行此程序,界面如下图所示

Android开发学习:[6]AlertDialog

5、然后我们点击Button3会出现三个选择按钮

Android开发学习:[6]AlertDialog

6、点击任意一个回出现Toast显示你点击了哪个按钮

Android开发学习:[6]AlertDialog

7、后面将继续介绍后续的三个AlterDialog欢迎继续关注。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢