Skip to content

Commit 08b9a09

Browse files
committed
Prevent mScrollY jumping on GridLayoutManager with 2+ columns.
1 parent 3c65189 commit 08b9a09

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

observablescrollview/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableRecyclerView.java

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,15 +96,24 @@ protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9696
super.onScrollChanged(l, t, oldl, oldt);
9797
if (mCallbacks != null) {
9898
if (getChildCount() > 0) {
99-
int firstVisiblePosition = getChildPosition(getChildAt(0));
100-
int lastVisiblePosition = getChildPosition(getChildAt(getChildCount() - 1));
99+
int firstVisiblePosition;
100+
int lastVisiblePosition;
101+
102+
if (getLayoutManager() instanceof LinearLayoutManager) {
103+
LinearLayoutManager manager = (LinearLayoutManager) getLayoutManager();
104+
firstVisiblePosition = manager.findFirstVisibleItemPosition();
105+
lastVisiblePosition = manager.findLastVisibleItemPosition();
106+
} else {
107+
throw new IllegalArgumentException("need to be an LinearLayoutManager child");
108+
}
109+
101110
for (int i = firstVisiblePosition, j = 0; i <= lastVisiblePosition; i++, j++) {
102111
if (mChildrenHeights.indexOfKey(i) < 0 || getChildAt(j).getHeight() != mChildrenHeights.get(i)) {
103112
mChildrenHeights.put(i, getChildAt(j).getHeight());
104113
}
105114
}
106115

107-
View firstVisibleChild = getChildAt(0);
116+
View firstVisibleChild = getChildAt(firstVisiblePosition);
108117
if (firstVisibleChild != null) {
109118
if (mPrevFirstVisiblePosition < firstVisiblePosition) {
110119
// scroll down

0 commit comments

Comments
 (0)