简体   繁体   中英

Raise event from DialogFragment to caller

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();

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 MainActivity or 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. Eg SubmitButton.Click -= SubmitButton_Click before you close the Fragment.

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