简体   繁体   中英

Android : How to dismiss a dialog when an item is selected

I found this library that implements the Material Design Dialogs, but the logic is defeating me somewhere. I want to dismiss the Dialog after an Item is selected.

Adapter is Created as follows.

MaterialSimpleListAdapter adapter = new MaterialSimpleListAdapter(new MaterialSimpleListAdapter.Callback() {
    @Override
    public void onMaterialListItemSelected(int i, MaterialSimpleListItem item) {
        long id     = item.getId();
        switch ((int) id){
            case 10 : Email();
        }
        ////I have to dismiss the dialog here, but its created below.
    }
});

Adding Item

adapter.add(new MaterialSimpleListItem.Builder(this)
                .content("Send by Email")
                .icon(R.mipmap.ic_mail_gray_48dp)
                .backgroundColor(Color.WHITE)
                .iconPaddingDp(8)
                .id(10)
                .build());

And then the dialog is created from adapter.

 MaterialDialog dialog = new MaterialDialog.Builder(this)
                .adapter(adapter, null)
                .autoDismiss(true)
                .show();

The problem is MaterialDialog is not yet created in the onMaterialListItemSelected since it depends on the adapter? How can I work this out?

显示对话框后,您可以通过以下方式将其关闭

dialog.dismiss();

I would suggest the following changes:

//declare as global the dialog variable
private MaterialDialog dialog;

final MaterialSimpleListAdapter adapter = new MaterialSimpleListAdapter(new MaterialSimpleListAdapter.Callback() {
            @Override
            public void onMaterialListItemSelected(int index, MaterialSimpleListItem item) {
                dialog.dismiss();
            }
        });

        //remove the autoDismiss(true) option, better use the Activity
        //context
        dialog = new MaterialDialog.Builder(MyActivity.this)
                .adapter(adapter, null)
                .show();

Hope it helps!!!

dialog.dismiss()

当您需要关闭它时。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM