比Toast更友好的对话框AlertDialog

来源:互联网 发布:花生壳软件下载 编辑:程序博客网 时间:2024/04/27 18:38

在调试过程中往往会弹出一个提示来提醒一个操作的状态,使用Toast时是会自动消失的,可能导致无法看到需要的信息。

 

而AlertDialog则是可以交互的对话框,使用起来更友好一些,一行代码的写法(与Toast相似的简洁哦~)

 

new AlertDialog.Builder(this).setTitle("Error").setMessage("Detail message.").setPositiveButton("OK", null).show();

当然还可以写的更复杂些:

 

new AlertDialog.Builder(this)
            .setTitle("Warning")
            .setMessage("Sure to reboot?")
            .setNegativeButton("Cancel", null)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String cmd = "su -c reboot";
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (Exception e){
                        Toast.makeText(getApplicationContext(), "Error! Fail to reboot.", Toast.LENGTH_SHORT).show();
                    }
                }
            })
            .show();   

0 0