Skip to content

Commit 823c34a

Browse files
committed
[Tab] Fix NPE caused by set a position less than 0
If somehow scroll position is set to -1 with and position offset greater than 0.5, we will decide it's a valid scroll position which causes NPE for selected child not found. Fixes this by checking if position is valid regardless the offset and falling back to 0 if a negative position is given. Resolves #2464 PiperOrigin-RevId: 408894188
1 parent 283715d commit 823c34a

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

lib/java/com/google/android/material/tabs/TabLayout.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,7 @@ public void setScrollPosition(
689689
if (scrollAnimator != null && scrollAnimator.isRunning()) {
690690
scrollAnimator.cancel();
691691
}
692-
scrollTo(calculateScrollXForTab(position, positionOffset), 0);
692+
scrollTo(position < 0 ? 0 : calculateScrollXForTab(position, positionOffset), 0);
693693

694694
// Update the 'selected state' view as we scroll, if enabled
695695
if (updateSelectedText) {
@@ -1881,11 +1881,14 @@ private void dispatchTabReselected(@NonNull final Tab tab) {
18811881
private int calculateScrollXForTab(int position, float positionOffset) {
18821882
if (mode == MODE_SCROLLABLE || mode == MODE_AUTO) {
18831883
final View selectedChild = slidingTabIndicator.getChildAt(position);
1884+
if (selectedChild == null) {
1885+
return 0;
1886+
}
18841887
final View nextChild =
18851888
position + 1 < slidingTabIndicator.getChildCount()
18861889
? slidingTabIndicator.getChildAt(position + 1)
18871890
: null;
1888-
final int selectedWidth = selectedChild != null ? selectedChild.getWidth() : 0;
1891+
final int selectedWidth = selectedChild.getWidth();
18891892
final int nextWidth = nextChild != null ? nextChild.getWidth() : 0;
18901893

18911894
// base scroll amount: places center of tab in center of parent

0 commit comments

Comments
 (0)