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

My question has been answered several times when it has TabActivity with tabWidgets . But I could not find anything regarding the relationally new TabLayout .

It's quite simple, just like on facebook, I want to click on a tab that is already selected so that my list scrolls up to its beginning. but I can’t figure out where to put the listener.

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


EDIT: Bugfix: As CommonsWare comments in a comment on his answer, I had to rewrite the "onTabSelected" behavior.

 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!

+5
source share
2 answers

Based on costs of ~ 10 seconds, read the documentation ... call setOnTabSelectedListener() in TabLayout . Go to the implementation of OnTabSelectedListener . Callback method onTabReselected() .

+13
source

In order not to lose the default behavior, 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 } }); 
+1
source

Source: https://habr.com/ru/post/1244744/


All Articles