Broken TabLayout due to ViewPager2

697 Views Asked by At

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: Breken TabLayout

1

There are 1 best solutions below

1
On

After trying many times with all sort of solutions i have found here, and trying with androidx.viewpager2:viewpager2:1.1.0-beta01 as well i had to rewrite my code using ViewPager and the deprecated FragmentStatePagerAdapter, following this solution.