Last active
November 7, 2022 23:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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