Android-AlertDialog - 不起作用

时间:2015-08-02 09:38:53

标签: android android-alertdialog

昨天我通过编程的AIDE编写了一个带有我的Android-Phone的AlertDialog。在互联网上,我找到了源代码

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to AndroidHive.info");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // Write your code here to execute after dialog closed
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});
// Showing Alert Message
alertDialog.show();

我已经在AIDE中对此进行了测试并且它正在运行,然后我在AndroidStudio中测试了它并且它没有工作。为什么它在AIDE中工作而不在Android工作室中?

1 个答案:

答案 0 :(得分:0)

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                AlertDialogActivity.this);

如上所述编辑第一行,因为您需要在创建alertDialog

之前设置构建器

完整代码如下:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");

// Setting Dialog Message
alertDialog.setMessage("Welcome to AndroidHive.info");

// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.tick);

// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        // Write your code here to execute after dialog closed
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
        }
});
AlertDialog alertDialogMain = alertDialog.create();

// Showing Alert Message
alertDialogMain.show();