0

I'm working on a Xamaran.Android project and try to implement a DialogFragment. I watched this video in order to set the Popup.

Here is the code of my DialogFragment :

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    base.OnCreateView(inflater, container, savedInstanceState);

    var view =  inflater.Inflate(Resource.Layout.WordChooser, container, false);

    SubmitButton = view.FindViewById<Button>(Resource.Id.SubmitButton);
    SubmitButton.Click += SubmitButton_Click;

    return view;
}

private void SubmitButton_Click(object sender, EventArgs e)
{

}

And here is my Activity caller :

private void FooButton_Click(object sender, EventArgs e)
{
    var trasaction = FragmentManager.BeginTransaction();
    WordChooser wordChooserDialog = new WordChooser();

    wordChooserDialog.Show(trasaction, "word chooser fragment");
}

I do not know how to set value from my DialogFragment to my Activity and close the DialogFragment. I tryed to use the second answer of this link but wasn't able to use getActivity();

Community
  • 1
  • 1
Xavier W.
  • 1,270
  • 3
  • 21
  • 47

1 Answers1

1

getXYZ and setXYZ get c#yfied. This means Xamarin is mapping getters and setters into properties. In your case getActivity is the getter of the property Activity of DialogFragment.

To pass data, you could

  • add a method DoSomething to your activity
  • cast the Activity to MainActivityor what ever your calling activity is
  • call DoSomething from your click listener

Dialog

private void SubmitButton_Click(object sender, EventArgs e)
{
    ((MainActivity) Activity).DoSomething("something");
    Dismiss();
}

Activity

public class MainActivity : Activity
{
    //...

    public void DoSomething(string something)
    {

    }
}

There are some other possible solutions, like

  • passing a callback to your Fragment
  • adding a event to your Fragment
  • ...

Important

Do not forget do deregister your event handlers. Every += should have a -=counterpart somewhere in your code. E.g. SubmitButton.Click -= SubmitButton_Click before you close the Fragment.

Sven-Michael Stübe
  • 14,560
  • 4
  • 52
  • 103
  • So I do not understand why on this Xamarin documentation [link](https://developer.xamarin.com/api/type/Android.App.DialogFragment/), there is a line of code like that : `((FragmentDialog)getActivity()).showDialog();` ? – Xavier W. Jul 13 '16 at 07:37
  • If you read carefully, you see, that these are **java examples**. I guess Xamarin is scraping the documentation from the google documentation. Beside the documentation stuff: Does my answer solve your problem? – Sven-Michael Stübe Jul 13 '16 at 12:29