MvvmCross-AndroidSupport
MvvmCross-AndroidSupport copied to clipboard
MvxCachingFragmentCompatActivity GetLastFragmentInfo() does not return the last added fragment.
I'm not sure if this is a bug or a misinterpretation, this is something that got me struggling for a while now.
Expected behavior
GetLastFragmentInfo() returning the last fragment that was added to it'sArrayList .
Actual behavior
FragmentManager.Fragments is an ArrayList and the indexes of this ArrayList change when a new fragment is added. However when a fragment is removed this ArrayList keeps it's indexes.
When a new fragment is added through the method ShowViewModel() the fragment is added where the index of the ArrayList is equal to null.
This means that the following line in GetLastFragmentInfo() does not return the last fragment add but the last fragment in the ArrayList:
var lastFragment = currentCacheableFragments.Last();
Configuration
Version: 4.2.0
Do you have any suggestions how to fix this? If we can't trust in the ArrayList's index, what do we do instead?
I'm looking for a way to fix this now.
SupportFragmentManager.Fragments is readonly so I can't reinitialize the ArrayList with other indexes.
One solution that I'm working on right now is saving the fragment Tag in method ShowFragment to a private property when the fragment is cacheable. This private property can be used to get the last added fragment in GetLastFragmentInfo.
Good start, and I think using a Queue to store the last tags is the only option. Your pull request misses stuff for the back navigation, currently it will not change the tag while navigating back.
To get the lastFragment in all scenario's right we need the following: ShowFragment needs to increase the queue (where you set the private field) OnBackPressed() and CloseFragment() need to decrease the queue.
PS: I made a quick work-around that works most of the time..... BUT sometimes it won't because the base. counts on SupportFragmentManager.Fragments and that collection isn't ordened like you would expect, so don't count on the order like done in the original GetLastFragmentInfo().
protected override IMvxCachedFragmentInfo GetLastFragmentInfo() { if (SupportFragmentManager.BackStackEntryCount == 0) return base.GetLastFragmentInfo() `` var backStackEntry = SupportFragmentManager.GetBackStackEntryAt(SupportFragmentManager.BackStackEntryCount - 1); return GetFragmentInfoByTag(backStackEntry.Name); }
I created a version that works with back navigation as well
#297