Skip to content

Instantly share code, notes, and snippets.

@modjke
Last active November 7, 2022 23:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save modjke/b652021679a2ed1935645a18102ab799 to your computer and use it in GitHub Desktop.
Save modjke/b652021679a2ed1935645a18102ab799 to your computer and use it in GitHub Desktop.
RecyclerView's LinearLayoutManager with the ability to set a fixed number of items to be displayed
package ;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
public class LinearLayoutPagerManager extends LinearLayoutManager {
private int mItemsPerPage;
public int getItemsPerPage()
{
return mItemsPerPage;
}
public LinearLayoutPagerManager(Context context, int orientation, boolean reverseLayout, int itemsPerPage) {
super(context, orientation, reverseLayout);
mItemsPerPage = itemsPerPage;
}
@Override
public boolean checkLayoutParams(RecyclerView.LayoutParams lp) {
return super.checkLayoutParams(lp) && lp.width == getItemSize();
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return setProperItemSize(super.generateDefaultLayoutParams());
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
return setProperItemSize(super.generateLayoutParams(lp));
}
private RecyclerView.LayoutParams setProperItemSize(RecyclerView.LayoutParams lp) {
int itemSize = getItemSize();
if (getOrientation() == HORIZONTAL) {
lp.width = itemSize;
} else {
lp.height = itemSize;
}
return lp;
}
private int getItemSize() {
int pageSize = getOrientation() == HORIZONTAL ? getWidth() : getHeight();
return Math.round((float) pageSize / mItemsPerPage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment