Skip to content

Instantly share code, notes, and snippets.

@bitristan
Created February 8, 2021 07:13
Show Gist options
  • Save bitristan/d4e1bc665853c73d5d5b7a45fb1fe663 to your computer and use it in GitHub Desktop.
Save bitristan/d4e1bc665853c73d5d5b7a45fb1fe663 to your computer and use it in GitHub Desktop.
A simple cusstom linearlayout manager
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
public class MyLinearLayoutManager extends RecyclerView.LayoutManager {
private int mOffsetY = 0;
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT,
RecyclerView.LayoutParams.WRAP_CONTENT);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
super.onLayoutChildren(recycler, state);
int offsetY = 0;
for (int i = 0; i < getItemCount(); i++) {
View view = recycler.getViewForPosition(i);
addView(view);
measureChildWithMargins(view, 0, 0);
int width = getDecoratedMeasuredWidth(view);
int height = getDecoratedMeasuredHeight(view);
int middleWidth = (getWidth() - width) / 2;
layoutDecorated(view, middleWidth, offsetY, middleWidth + width, offsetY + height);
offsetY += height;
}
}
@Override
public boolean canScrollVertically() {
return true;
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler,
RecyclerView.State state) {
int offset = dy;
if (mOffsetY + dy < 0) {
offset = -mOffsetY;
}
mOffsetY += offset;
offsetChildrenVertical(-offset);
return offset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment