From 823c34a90c97828115e147d482c544bdee6c2b57 Mon Sep 17 00:00:00 2001 From: conradchen Date: Wed, 10 Nov 2021 12:07:08 -0500 Subject: [PATCH] [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 https://github.com/material-components/material-components-android/issues/2464 PiperOrigin-RevId: 408894188 --- lib/java/com/google/android/material/tabs/TabLayout.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/java/com/google/android/material/tabs/TabLayout.java b/lib/java/com/google/android/material/tabs/TabLayout.java index 5d507a348a7..9bb1f36e159 100644 --- a/lib/java/com/google/android/material/tabs/TabLayout.java +++ b/lib/java/com/google/android/material/tabs/TabLayout.java @@ -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) { @@ -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