croxy croxy - 3 months ago 31
C# Question

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. The whole content is shown in the different fragments.

One of the fragments is displaying a list of users. I want to provide a filter for this list. So I created a new fragment with all the filter options and a button which should apply all the filters on the previous "User-List-Fragment".

I display the "filter" fragment by adding a
frame
to my "User-List-Fragment" and load the "filter" fragment into it:

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


To apply the filter I call

FragmentManager.PopBackStack();


in the "click event listener" of the "apply filter button", to display the "User-List-Fragment" again. But here it all comes to an sudden end because I don't know if or how I can populate the filter data back to my "User-List-Fragment".

This is a part of my
.axml
layout of the "User-List-Fragment". The
<FrameLayout />
overlays the
<ListView />
and gets only visible if the user presses the "filter button".

.
.
.
<ListView
android:id="@+id/members_listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="150dp" />

<FrameLayout
android:id="@+id/members_filterFrame"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone" />
.
.
.


Question

Is it possible to populate data from the
FilterFragment
back to the "User-List-Fragment" when calling
FragmentManager.PopBackStack();
?

If so, how?

Answer

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, new FilterFragment((parameter) => {
    // Do something with the given parameter
}))
.Commit();

FilterFragment

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

public override void OnDestroyView()
{
    base.OnResume();

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