I have a Tablayout
with 2 tabs (fragments) Home and Contacts, implemented using aViewPager2
. The data in each fragment (an update is requested on each onResume()
of the TabLayout Activity).Since i have to call adapter.notifyItemChanged(position);
to refresh the fragments, i had to overrite both getItemId
and containsItem
in my FragmentStateAdpater
as explained in the blue note in this section .
The problem is that now the TabLayout is broken, if i switch tab then the menu inflated in the previous tab remains (so for instance the search menu item remains when switching from Conctacts) and by printing some logs i noticed that it goes in a loop. Without overriding the getItemId
and containsItem
the tablayout works properly but the data is not refreshed when updated.
@Override
public long getItemId(int position) {
String tag = "f" + position;
if (fragmentManager.findFragmentByTag(tag) != null) {
Log.i("TEST", fragmentManager.findFragmentByTag(tag).toString() + " at position " + position);
return (long) fragmentManager.findFragmentByTag(tag).hashCode();
}
return super.getItemId(position);
}
@Override
public boolean containsItem(long itemId) {
Log.i("TEST", "Here is " + itemId);
Log.i("TEST", "Here is " + fragmentManager.getFragments().stream().anyMatch(fragment -> (long) fragment.hashCode() == itemId));
//return super.containsItem(itemId);
return fragmentManager.getFragments().stream().anyMatch(fragment -> fragment.hashCode() == itemId);
}
Maybe taking the hash of the fragment isn't a unique ID since the fragment is created using an object (BusinessCard.newInstance(myContact);
) and the second one a list ContactList.newInstance(listContacts);
.
Any help would be really useful since i am completely lost.
Thank you very much!
EDIT:
If i switch to Contacts tab it starting looping. Logs:
I/TEST: Here is 1
I/TEST: Here is false
I/TEST: Here is 1
I/TEST: Here is false
I/TEST: ContactList{7e700e} (48ea6f92-44ca-4324-8079-325c865df43e tag=f1) at position 1
I/TEST: ContactList{7e700e} (48ea6f92-44ca-4324-8079-325c865df43e tag=f1) at position 1
And in the picture you can visualize the problem. In the Home fragment the search item menu should not be present. It persist after switching back from Contacts to Home: