Skip to content

Commit

Permalink
[Tab] Fix NPE caused by set a position less than 0
Browse files Browse the repository at this point in the history
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
  • Loading branch information
drchen committed Nov 10, 2021
1 parent 283715d commit 823c34a
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/java/com/google/android/material/tabs/TabLayout.java
Expand Up @@ -689,7 +689,7 @@ public void setScrollPosition(
if (scrollAnimator != null && scrollAnimator.isRunning()) {
scrollAnimator.cancel();
}
scrollTo(calculateScrollXForTab(position, positionOffset), 0);
scrollTo(position < 0 ? 0 : calculateScrollXForTab(position, positionOffset), 0);

// Update the 'selected state' view as we scroll, if enabled
if (updateSelectedText) {
Expand Down Expand Up @@ -1881,11 +1881,14 @@ private void dispatchTabReselected(@NonNull final Tab tab) {
private int calculateScrollXForTab(int position, float positionOffset) {
if (mode == MODE_SCROLLABLE || mode == MODE_AUTO) {
final View selectedChild = slidingTabIndicator.getChildAt(position);
if (selectedChild == null) {
return 0;
}
final View nextChild =
position + 1 < slidingTabIndicator.getChildCount()
? slidingTabIndicator.getChildAt(position + 1)
: null;
final int selectedWidth = selectedChild != null ? selectedChild.getWidth() : 0;
final int selectedWidth = selectedChild.getWidth();
final int nextWidth = nextChild != null ? nextChild.getWidth() : 0;

// base scroll amount: places center of tab in center of parent
Expand Down

0 comments on commit 823c34a

Please sign in to comment.