Cannot get DialogFragment to dismiss programmatically

浪尽此生 提交于 2019-12-01 06:46:28

For some - unknown to me - reason, the dialog reference you get back from getDialog() isn't the one you want to work with when inside the listener. You need a reference to the dialog as provided you when you call builder.create();

For example:

    final AlertDialog dialog = builder.create();
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            dialog.dismiss();
        }
    });
    return dialog;

Why not use the methods available on AlertDialog.Builder to build the list, instead of creating your own ListView and populating it?

I have modified your sample code to show how this would work, and in this example the dialog dismiss() functions fine.

public Dialog onCreateDialog(android.os.Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setSingleChoiceItems(mShareAdapter, 0, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (listener != null) {
                    listener.newShare((ShareType) mShareAdapter.getItem(which));
                }
            }
        });
        builder.setTitle("Share which?");
        return builder.create();
    }

HA....

I've found it...

The reason for this is actually ours... we were trying to inflate an xml, and have called:

DialogFragment.this.getLayoutInflater(null).inflate(...);

This call causes, like I've stated in the comment to create 4 dialogs, and then everything gets messed up.

The proper way to do this would be to call:

LayoutInflater layoutInflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(...);

This fix solved the annoying bug for me on the first go!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!