Search code examples
androidandroid-tablayout

Facing Issue with Android TabLayout Tabs Click


I implemented a TabLayout having three Tabs. When I Swipe the Pages Everything Work Fine, it also works when I only use tab clicks to navigate. But the problem arise when I Swipe the page and click on any of the previously selected tab, only the tab indicator changes to the new tab but the text highlight and the pages are not changing.

I Checked the click listener of the TabLayout, it is not executing in the above situation.

More Info:

minSdk:16
targetSdk:24

I tried support libraries 24.0.0 and 24.1.1

TabSelectedListener.

        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            tabPages.setCurrentItem(tab.getPosition());
        }

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

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

PagerAdapter

public class TabPageAdapter extends FragmentStatePagerAdapter {
public TabPageAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    Fragment f1 = new Fragment1();
    Fragment f2 = new Fragment2();
    Fragment f3 = new Fragment3();

    switch (position) {
        case 0:
            return f1;
        case 1:
            return f2;
        case 2:
            return f3;
    }
    return null;
}


@Override
public int getCount() {
    return 3;
}

}


Solution

  • You can avoid the OnTabSelectedListener entirely, TabLayout has a convenience method for this:

    tabs.setupWithViewPager(tabPages);