Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 768
Renaud Favier Avatar asked Mar 09 '16 15:03

Renaud Favier


1 Answers

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

like image 107
CommonsWare Avatar answered Oct 21 '22 12:10

CommonsWare