Damn Vegetables
Damn Vegetables

Reputation: 12504

TabLayout does not reflect ViewPager adapter's change

I want a tabbed dialogue box. So I added a TabLayout, and a ViewPager below it. I created a FragmentPagerAdapter, and called the ViewPager's setAdapter() with it. Then I called TabLayout's setupWithViewPager() with the ViewPager.

Now, I increased the count of the FragmentPagerAdapter, and added a new fragment to it, and called notifyDataSetChanged(). The problem is that new tab did not appear.

After trying a lot of things, I called the TabLayout's setupWithViewPager() again with the same ViewPager. It did make the new tab appear, but I am not sure whether this is the correct approach. Why doesn't the TabLayout automatically reflect the changes to the ViewPager (new fragment)?

Upvotes: 2

Views: 1177

Answers (2)

rajesh
rajesh

Reputation: 41

You need to add Observer as suggested above. Add a new tab for the new added item in your this.mAdapter used by your this.viewPager and this.tabLayout.

       mAdapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            if (tabLayout.getTabCount() < mAdapter.getCount()) {
                tabLayout.addTab(tabLayout.newTab().setText(mAdapter.getPageTitle(mAdapter.getCount() - 1)), mAdapter.getCount() - 1);
            }
        }
    });

Upvotes: 0

convexHull
convexHull

Reputation: 1881

Your solution is quite simple, but needs one more thing. If you can see what method setupWithViewPager() does, it also adds TabLayoutOnPageChangeListener to viewPager, so whenever you call setupWithViewPager() you add one more listener. You should call viewPager.clearOnPageChangeListeners() to remove old lisetners, just before you call setupWithViewPager() and it will be ok.

In project, I'm working on, we are using a bit different solution, but it is because of using custom tab views with some specific behavior: You can registerDataSetObserver on your viewpageradapter. Whenever you call notifyDataSetChanged() your DataSetObserver.onChanged() will be called too. In this method we are manipulating with tabs in tablayout (creating new/removing old).. We also create new onTabSelectedListeners for tabLayout.

Upvotes: 2

Related Questions