Skip to content

Commit

Permalink
Android: impl scroll to item with top offset api
Browse files Browse the repository at this point in the history
  • Loading branch information
jingpeng authored and penfeizhou committed Aug 3, 2023
1 parent 3dd44cf commit 411ca69
Showing 1 changed file with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;

Expand Down Expand Up @@ -472,7 +473,12 @@ public void scrollToItem(JSObject params) {
animated = params.getProperty("animated").asBoolean().value();
}
JSNumber pos = params.getProperty("index").asNumber();
moveToPosition(pos.toInt(), animated);
JSValue topOffsetValue = params.getProperty("topOffset");
if (topOffsetValue.isNumber()) {
moveToPositionWithTopOffset(pos.toInt(), animated, topOffsetValue.asNumber().toFloat());
} else {
moveToPosition(pos.toInt(), animated);
}
}

@DoricMethod
Expand Down Expand Up @@ -537,6 +543,11 @@ private void moveToPosition(int pos, boolean smooth) {
}
}

private void moveToPositionWithTopOffset(int pos, boolean animated, float topOffset) {
RecyclerView.SmoothScroller smoothScroller = new OffsetLinearSmoothScroller(getContext(), DoricUtils.dp2px(-topOffset));
smoothScroller.setTargetPosition(pos);
Objects.requireNonNull(mView.getLayoutManager()).startSmoothScroll(smoothScroller);
}

private void defaultScrollTo(int pos, boolean b) {
if (b) {
Expand Down Expand Up @@ -714,4 +725,23 @@ public int calculateDyToMakeVisible(View view, int snapPreference) {
return calculateDtToFit(top, bottom, start, end, snapPreference);
}
}

private static class OffsetLinearSmoothScroller extends LinearSmoothScroller {
private final int offset;

public OffsetLinearSmoothScroller(Context context, int offset) {
super(context);
this.offset = offset;
}

@Override
public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
return boxStart - viewStart + offset;
}

@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
}
}

0 comments on commit 411ca69

Please sign in to comment.