开发者

Find the parent Dialog of a Button

I have an alert dialog which contains a button. The button is defined in some XML and the layout is set using Dialog.setContentView().

The button has a listener class and I want to know how, if at all, I can access the dialog from the onClick(View v) method.

The reason for this is simply that I want to be able to dismiss the dialog - so if there's an easie开发者_StackOverflowr/better way to do this then that would be useful to know!


Simple solution using the onCreateDialog() method from the Activity class:

// member variable
Dialog mDialog;

protected Dialog onCreateDialog(int id) {
    Builder builder = new AlertDialog.Builder(mContext);
    switch (id) {
        case DELETE_ALL_DIALOG:
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.ok, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //do what you want
                }
            });
            builder.setNegativeButton(R.string.cancel, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismissDialog(DELETE_ALL_DIALOG); // thats what you are looking for
                }
            });
            builder.setMessage(R.string.delete_all_bookmarks_question);
            mDialog = builder.create();
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            return mDialog;
        default:
            return super.onCreateDialog(id);
    }
}


Create a custom dialog class and define the button in there. Something like:

public class CustomizeDialog extends Dialog implements OnClickListener {
    Button okButton;

    public CustomizeDialog(Context context) {
        super(context);
        /** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        /** Design the dialog in main.xml file */
        setContentView(R.layout.main);
        okButton = (Button) findViewById(R.id.OkButton);
        okButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        /** When OK Button is clicked, dismiss the dialog */
        if (v == okButton)
            dismiss();
    }


For now I've simply passed a reference to the dialog into the listener class and then called dismiss() at the appropriate time.

This doesn't seem like the best way - is there a better one?

Creating a custom dialog seems unnecessary to me... It doesn't need anything out of the ordinary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜