Reputation: 1005
I am using TabLayout in my project which might have more than 10 TabItems. Now I wanted to hide an other view when the user scroll the TabLayout.
Note: I am not using any ViewPager.
Upvotes: 2
Views: 5145
Reputation: 699
Finally i got the solution when your scroll till last tab is visible. Below is the code given. Hope it will help.
val lastTabIndex = yourTabLayout.tabCount - 1
val lastTab = yourTabLayout.getTabAt(lastTabIndex)
yourTabLayout.getViewTreeObserver().addOnScrollChangedListener {
val scrollX = yourTabLayout.scrollX
val tabsWidth = yourTabLayout.getChildAt(0).width
val tabsViewWidth = yourTabLayout.width
if (scrollX + tabsViewWidth >= tabsWidth) {
// Tabs are scrolled to the right end
// You can perform any actions you need here
// Get the last tab and do whatever you need with it
lastTab?.let {
//perform the action with last tab
}
}else{
/* Write the code when your are not in last tab position.
*/
}
}
Upvotes: 0
Reputation: 3622
TabLayout has its own functionality for tab change listener callback. Use
onPageChange Listener:
TabLayout.TabLayoutOnPageChangeListener(TabLayout tabLayout)
Check this link: OnTabChange Listener for more information
onTabSelected Listener:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
@Override
public void onTabSelected(TabLayout.Tab tab){
int position = tab.getPosition();
}
});
Check for more: onTabSelected Listener
Upvotes: 1
Reputation: 729
Every instance of View calls getViewTreeObserver()
. You can add an OnScrollChangedListener()
to it by using addOnScrollChangedListener()
.
In your case:
tabLayout.getViewTreeObserver().addOnScrollChangedListener(() -> {
int scrollX = tabLayout.getScrollX(); // Current x scrolling position
// We know that we have at least one child
int maxScrollWidth = categoryTabLayout.getChildAt(0).getMeasuredWidth() - windowSize.x;
// Do whatever you want here
});
windowSize is a Point accessed from the WindowManager
private Point windowSize = new Point();
// Calculate the position if this window
getActivity().getWindowManager().getDefaultDisplay().getSize(windowSize);
By using the approach above you will have updates about the proper scroll position you need
Upvotes: 4
Reputation: 162
If you're using your TabLayout with a ViewPager like this:
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
Then you can use:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels){
}
@Override
public void onPageSelected(int position){
}
@Override
public void onPageScrollStateChanged(int state){
}
});
And in the method onPageSelected(), you can do the action you want depending on the tab showing.
Upvotes: 0