Renaud Favier
Renaud Favier

Reputation: 1655

How to detect a click on an already selected tab in TabLayout

My question has been answered several times when it's a TabActivity with tabWidgets. But I couldn't find anything about the relativly new TabLayout view.

It's quite simple, like facebook, I want a tap on an already selected tab to get my list to scroll up til its beggining. but I can't figure out where to put my listener.

I tried on the TabLayout itself, mTabLayout.getChildAt() and on TabLayout.getTabAt().getCustomView().


EDIT : Correction : As CommonsWare mentionned in the comment of its answer, I had to rewrite the behaviour of "onTabSelected".

mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);

for (int i = 0; i < mTabLayout.getTabCount(); i++) {
    mTabLayout.getTabAt(i).setIcon(tabIcons[i]);
}

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

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

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        if (tab.getPosition() == PAGE_FEED) {
                ((PagerNewsFeedFragment) mViewPagerAdapter.getRegisteredFragment(PAGE_FEED)).scrollToTop();
            }
    }
});

Thanks !

Upvotes: 5

Views: 6013

Answers (2)

urSus
urSus

Reputation: 12739

To not lose the default behaviour use it like this

TabLayout tabLayout = findById(this, R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        // Scroll to top or whatever
    }
});

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1006869

Based on spending ~10 seconds reading the documentation... call setOnTabSelectedListener() on the TabLayout. Pass in an OnTabSelectedListener implementation. Your event callback method is onTabReselected().

Upvotes: 17

Related Questions