Search code examples
c#androidxamarin.androidandroid-dialogfragmentdialogfragment

Xamarin Android - Dismiss DialogFragment


I have looked on several different threads on how to dismiss a DialogFragment but nothing seems to work for me. I want to be able to close the DialogFragment when I switch to a new Activity from the click event that I have. I tried by using something like this.Activity.Dismiss() from the click event but also tried this from where I show the DialogFragment:

if (_exportFragment != null)
            {
                _exportFragment.Dismiss();
            }

But none of these seem to work.

EDIT

This is where I display the DialogFragment:

gridview.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args)
            {
                // DIALOG FRAGMENT
                FragmentTransaction ft = FragmentManager.BeginTransaction();
                //Remove fragment else it will crash as it is already added to backstack
                Fragment prev = FragmentManager.FindFragmentByTag("dialog");
                if (prev != null)
                {
                    ft.Remove(prev);
                }

                ft.AddToBackStack(null);

                // Create and show the dialog.
                _exportFragment = new VideoExportDialogFragment();
                _exportFragment.VideoCreationDate = VideoList[args.Position].CreationDate;
                //_exportFragment.
                _exportFragment.VideoPathFragment = VideoListPosition(args.Position);

                //_exportFragment.ThumbnailActivity = this;
                //Add fragment
                _exportFragment.Show(ft, "dialog");
                dismissLoader();
            };
        }

        private void dismissLoader()
        {
            if (_exportFragment != null)
            {
                _exportFragment.Dismiss();
            }
        }

Solution

  • I want to be able to close the DialogFragment when I switch to a new Activity from the click event that I have.

    In this click event, you could find the dialogFragment that you want to close by using FindFragmentByTag("dialog") method, then you could use _exportFragment.Dismiss() to dismiss this DialogFragment. Code like this :

    bt.Click += (sender, e) =>
    {
         MyDialogFragment _exportFragment = (MyDialogFragment)FragmentManager.FindFragmentByTag("dialog");
         if (_exportFragment != null)
         {
               _exportFragment.Dismiss();
         }
         //StartActivity(you);
    };