Skip to content Skip to sidebar Skip to footer

Is It Possible To Return Data To The Previous Fragment When "fragmentmanager.popbackstack()" Is Called?

I'm developing an app with Xamarin.Android in which I have a root activity including a frame for displaying different fragments. The root activity contains only navigation items. T

Solution 1:

You should be able to pass an Action to your FilterFragment.

When OnDestroyView() is called you can invoke the Action and send back data.


Example

First Fragment

FragmentManager.BeginTransaction()
.AddToBackStack(null)
.Replace(Resource.Id.members_filterFrame, newFilterFragment((parameter) => {
    // Do something with the given parameter
}))
.Commit();

FilterFragment

private Action<T> _onCompletionAction;
publicFilterFragment(Action<T> onCompletionAction) 
{
    _onCompletionAction = onCompletionAction;
}

publicoverridevoidOnDestroyView()
{
    base.OnResume();

    _onCompletionAction(parameter) // parameter could be a filter object.
}

Solution 2:

I solved it by firing an event with custom EventArgs after pressing the "apply filter button" in the FilterFragment:

Searched?.Invoke(this, newFilterAppliedEventArgs(FilterObject)); // fire search event
FragmentManager.PopBackStack();

The FilterAppliedEventArgs class looks like:

publicclassFilterAppliedEventArgs : EventArgs
{
    public Filter FilterObject { get; set; }

    public FilterAppliedEventArgs(Filter filter)
    {
        this.FilterObject = filter;
    }
}

And registering the event in the "User-List-Fragment" before displaying the FilterFragment like this:

var filterFragment = newFilterFragment();
// get the filter attributes
filterFragment.Searched += (s, ea) =>
{
   var eventArgs = ea asFilterAppliedEventArgs;
   LoadFilteredMembers(eventArgs.FilterObject);
};

FragmentManager.BeginTransaction()
   .AddToBackStack(null)
   .Replace(Resource.Id.members_filterFrame, filterFragment)
   .Commit();

The approach from @Pilatus seems very handy too. Both will work and I don't know which one is the better one.

Post a Comment for "Is It Possible To Return Data To The Previous Fragment When "fragmentmanager.popbackstack()" Is Called?"