Changing number of columns in RecyclerView gridlayout

Umer Farooq picture Umer Farooq · Jan 2, 2015 · Viewed 16.6k times · Source

I am trying to change the number of columns that appear in the recycler view (grid layout) based on the display size. However I couldn't figure out a proper way of achieving it. At the moment I am using treeViewObserver to change the number of columns based the change in screen size (during orientation). So if the app opens in portrait mode, number of columns (on the phone) it decides to be one, which look good but this method doesn't work when the app directly opens in landscape mode where a single streched out card in the grid is displayed on the screen.

Here recList is RecyclerView & glm is GridLayoutManager used in RecyclerView

    viewWidth = recList.getMeasuredWidth();

    cardViewWidthZZ = recList.getChildAt(0).getMeasuredWidth();

    if (oldWidth == 0) {
        oldWidth = cardViewWidthZZ;
    }

    if (oldWidth <= 0)
        return;

    int newSpanCount = (int) Math.floor(viewWidth / (oldWidth / 1.3f));
    if (newSpanCount <= 0)
        newSpanCount = 1;
    glm.setSpanCount(newSpanCount);
    glm.requestLayout();

Best Regards

Answer

jasxir picture jasxir · Jul 1, 2015
public class VarColumnGridLayoutManager extends GridLayoutManager {

private int minItemWidth;

public VarColumnGridLayoutManager(Context context, int minItemWidth) {
    super(context, 1);
    this.minItemWidth = minItemWidth;
}

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler,
        RecyclerView.State state) {
    updateSpanCount();
    super.onLayoutChildren(recycler, state);
}

private void updateSpanCount() {
    int spanCount = getWidth() / minItemWidth;
    if (spanCount < 1) {
        spanCount = 1;
    }
    this.setSpanCount(spanCount);
}}