@@ -168,6 +168,7 @@ public void forceTransitionToPosition(int position){
168
168
return ;
169
169
}
170
170
mTabStrip .onTabsViewPagerPageChanged (position , 0 );
171
+ makeTabVisible (position , true );
171
172
}
172
173
173
174
/**
@@ -423,6 +424,54 @@ private void scrollToTab(int tabIndex, int positionOffset) {
423
424
}
424
425
}
425
426
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
+
426
475
private class InternalViewPagerListener extends OnPageChangeCallback {
427
476
private int mScrollState ;
428
477
@@ -434,7 +483,7 @@ public void onPageScrolled(int position, float positionOffset, int positionOffse
434
483
}
435
484
mTabStrip .onTabsViewPagerPageChanged (position , positionOffset );
436
485
if (positionOffset == 0 && mScrollState == androidx .viewpager .widget .ViewPager .SCROLL_STATE_SETTLING ) {
437
- scrollToTab (position , 0 );
486
+ makeTabVisible (position );
438
487
}
439
488
}
440
489
0 commit comments