NSouth NSouth - 6 months ago 28
Android Question

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;
}
});

Answer

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

tabLayout.getTabAt(0).select();