安卓如何关闭自定义对话框

21

我试图在按钮按下时关闭自定义对话框。

        //set up dialog
        Dialog dialog = new Dialog(BrowseActivity.this);
        dialog.setContentView(R.layout.about);
        dialog.setTitle("This is my custom dialog box");
        dialog.setCancelable(true);
        //there are a lot of settings, for dialog, check them all out!

        //set up text
        TextView text = (TextView) dialog.findViewById(R.id.TextView01);
        text.setText(R.string.app_help_message);

        //set up image view
        ImageView img = (ImageView) dialog.findViewById(R.id.ImageView01);
        img.setImageResource(R.drawable.icon);

      //set up button
        Button button = (Button) dialog.findViewById(R.id.Button01);
        button.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {
            Dialog.dismiss();

            }
        });

        //now that the dialog is set up, it's time to show it    
        dialog.show();

       return true;

dialog.dismiss()对我不起作用。我只是想将这个自定义对话框用作帮助屏幕,并希望按下按钮来关闭它。

我很新于Android开发,但已经尝试了很多小时。

谢谢任何建议。


你需要在对话框实例上调用dismiss方法(该实例是使用Dialog dialog = new Dialog(BrowseActivity.this)创建的),而不是在Dialog类上调用。 - A.B.
2个回答

34
final Dialog dialog = new Dialog(BrowseActivity.this);
你需要小写字母的对话框。
public void onClick(View v) {
   dialog.dismiss();
}

同时,AlertDialog.Builder 可能更适合您的需求。


好的,问题解决了。我已经在关于页面使用了AlertDialog.Builder,但是无法弄清如何为其设置布局。就像我说的,这对我来说都是新的,我很惊讶自己能走到这一步。我会继续阅读。 - user639410

3
您可以在对话框上调用dismiss()方法。 我这样做有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接