Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabLayout tab text not highlighted after viewPager.setCurrentItem()

I'm having an issue with the TabLayout attached to my ViewPager. Repro steps:

  1. Start on the first tab.
  2. Select the 2nd tab.
  3. Press the back button--my code sees that the user is on the second tab and calls viewPager.setCurrentItem(0) to return the user to the first tab.
  4. However, as shown in the picture, the 2nd tab text is still selected while the 1st tab text is grayed out. (Although the pink bar goes back to the 1st tab like it should.)

enter image description here

What am I missing?

tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout_main);
tabLayout.addTab(tabLayout.newTab().setText(getActivity().getString(R.string.main_tab_grades)));
tabLayout.addTab(tabLayout.newTab().setText(getActivity().getString(R.string.main_tab_schedule)));

viewPager = (NonSwipeableViewPager) rootView.findViewById(R.id.pager_main);
pagerAdapter = new PagerAdapterMain(getActivity(), getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);

viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }


    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        return;
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        return;
    }
});
like image 712
NSouth Avatar asked Feb 15 '16 23:02

NSouth


Video Answer


2 Answers

Maybe it is a bug of Design Library. As the issue said: https://code.google.com/p/android/issues/detail?id=192834

And the codes worked for me :

// mViewPager.setCurrentItem(position);

mTabLayout.getTabAt(position).select();
like image 132
BinqiangSun Avatar answered Oct 17 '22 17:10

BinqiangSun


you could try to select the tab through the tablayout instead of the viewPager.

tabLayout.getTabAt(0).select();
like image 5
Edwin Avatar answered Oct 17 '22 18:10

Edwin