Skip to content

Commit 4cf1563

Browse files
authored
Merge pull request #474 from nativescript-community/fix/tabs-bar-scrolling
fix: lazy tab bar slow with or without animations
2 parents 75e7b54 + e51e5c9 commit 4cf1563

File tree

1 file changed

+50
-1
lines changed
  • packages/core-tabs/platforms/android/java/com/nativescript/material/core

1 file changed

+50
-1
lines changed

packages/core-tabs/platforms/android/java/com/nativescript/material/core/TabsBar.java

+50-1
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ public void forceTransitionToPosition(int position){
168168
return;
169169
}
170170
mTabStrip.onTabsViewPagerPageChanged(position, 0);
171+
makeTabVisible(position, true);
171172
}
172173

173174
/**
@@ -423,6 +424,54 @@ private void scrollToTab(int tabIndex, int positionOffset) {
423424
}
424425
}
425426

427+
private void makeTabVisible(int tabIndex) {
428+
makeTabVisible(tabIndex, true);
429+
}
430+
431+
private void makeTabVisible(int tabIndex, boolean smoothScroll) {
432+
final int tabStripChildCount = mTabStrip.getChildCount();
433+
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
434+
return;
435+
}
436+
437+
View selectedChild = mTabStrip.getChildAt(tabIndex);
438+
if (selectedChild == null) {
439+
return;
440+
}
441+
int selectedLeft = selectedChild.getLeft();
442+
int selectedRight = selectedChild.getRight();
443+
444+
int myWidth = getWidth();
445+
446+
// add padding to the sides so it's clear that we have more tabs to scroll to
447+
if (tabIndex > 0) {
448+
selectedLeft = selectedLeft - mTitleOffset;
449+
}
450+
if (tabIndex < tabStripChildCount - 1) {
451+
selectedRight = selectedRight + mTitleOffset;
452+
}
453+
454+
int scrollX = getScrollX();
455+
if (selectedLeft < scrollX && selectedRight > myWidth + scrollX) {
456+
// the tab is already visible and can't fit the screen, no need to scroll
457+
return;
458+
}
459+
460+
if (selectedLeft < scrollX) {
461+
if (smoothScroll) {
462+
smoothScrollTo(selectedLeft, 0);
463+
} else {
464+
scrollTo(selectedLeft, 0);
465+
}
466+
} else if (selectedRight > myWidth + scrollX) {
467+
if (smoothScroll) {
468+
smoothScrollTo(selectedRight - myWidth, 0);
469+
} else {
470+
scrollTo(selectedRight - myWidth, 0);
471+
}
472+
}
473+
}
474+
426475
private class InternalViewPagerListener extends OnPageChangeCallback {
427476
private int mScrollState;
428477

@@ -434,7 +483,7 @@ public void onPageScrolled(int position, float positionOffset, int positionOffse
434483
}
435484
mTabStrip.onTabsViewPagerPageChanged(position, positionOffset);
436485
if (positionOffset == 0 && mScrollState == androidx.viewpager.widget.ViewPager.SCROLL_STATE_SETTLING) {
437-
scrollToTab(position, 0);
486+
makeTabVisible(position);
438487
}
439488
}
440489

0 commit comments

Comments
 (0)