GridLayoutManager - how to auto fit columns?

夙愿已清 提交于 2019-11-27 10:56:11
Riten

You can calculate available number of columns, given a desired column width, and load the image as calculated. Define a static funtion to calculate as:

public class Utility {
    public static int calculateNoOfColumns(Context context, float columnWidthDp) { // For example columnWidthdp=180
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float screenWidthDp = displayMetrics.widthPixels / displayMetrics.density;
        int noOfColumns = (int) (screenWidthDp / columnWidthDp + 0.5); // +0.5 for correct rounding to int.
        return noOfColumns;
    }
}

And then when using it in the activity or fragment you can do like this :

int mNoOfColumns = Utility.calculateNoOfColumns(getApplicationContext());

............
mGridLayoutManager = new GridLayoutManager(this, mNoOfColumns);

The GridLayoutManager's constructor has an argument spanCount that is

The number of columns in the grid

You can initialize the manager with an integer resource value and provide different values for different screens (i.e. values-w600, values-large, values-land).

I tried @Riten answer and worked funtastic!! But I wasn't happy with the hardcoded "180" So I modified to this:

    public class ColumnQty {
    private int width, height, remaining;
    private DisplayMetrics displayMetrics;

    public ColumnQty(Context context, int viewId) {

        View view = View.inflate(context, viewId, null);
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        width = view.getMeasuredWidth();
        height = view.getMeasuredHeight();
        displayMetrics = context.getResources().getDisplayMetrics();
    }
    public int calculateNoOfColumns() {

        int numberOfColumns = displayMetrics.widthPixels / width;
        remaining = displayMetrics.widthPixels - (numberOfColumns * width);
//        System.out.println("\nRemaining\t" + remaining + "\nNumber Of Columns\t" + numberOfColumns);
        if (remaining / (2 * numberOfColumns) < 15) {
            numberOfColumns--;
            remaining = displayMetrics.widthPixels - (numberOfColumns * width);
        }
        return numberOfColumns;
    }
    public int calculateSpacing() {

        int numberOfColumns = calculateNoOfColumns();
//        System.out.println("\nNumber Of Columns\t"+ numberOfColumns+"\nRemaining Space\t"+remaining+"\nSpacing\t"+remaining/(2*numberOfColumns)+"\nWidth\t"+width+"\nHeight\t"+height+"\nDisplay DPI\t"+displayMetrics.densityDpi+"\nDisplay Metrics Width\t"+displayMetrics.widthPixels);
        return remaining / (2 * numberOfColumns);
    }
}

Where "viewId" is the layout to be used as views in the RecyclerView like in R.layout.item_for_recycler

Not sure though about the impact of View.inflate as I only use it to get the Width, nothing else.

Then on the GridLayoutManager I do:

GridLayoutManager gridLayoutManager = new GridLayoutManager(this, Utility.columnQty(this, R.layout.item_for_recycler));

UPDATE: I added more lines to the code as I use it to get a minimum width spacing in the Grid. Calculate spacing:

recyclerPatternsView.addItemDecoration(new GridSpacing(columnQty.calculateSpacing()));

Constructor new GridLayoutManager(activity, 2) is about GridLayoutManager(Context context, int spanCount) where spanCount is the number of columns in the grid.

Best way is to check window/view width and base on this width count how many spans you want to show.

Use this function, and put margins for cell layout in XML instead using decoration.

public int getNumberOfColumns() {
        View view = View.inflate(this, R.layout.row_layout, null);
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int width = view.getMeasuredWidth();
        int count = getResources().getDisplayMetrics().widthPixels / width;
        int remaining = getResources().getDisplayMetrics().widthPixels - width * count;
        if (remaining > width - 15)
            count++;
        return count;
    }
public class AutoFitGridLayoutManager extends GridLayoutManager {

private int columnWidth;
private boolean columnWidthChanged = true;

public AutoFitGridLayoutManager(Context context, int columnWidth) {
    super(context, 1);

    setColumnWidth(columnWidth);
}


public void setColumnWidth(int newColumnWidth) {
    if (newColumnWidth > 0 && newColumnWidth != columnWidth) {
        columnWidth = newColumnWidth;
        columnWidthChanged = true;
    }
}

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    if (columnWidthChanged && columnWidth > 0) {
        int totalSpace;
        if (getOrientation() == VERTICAL) {
            totalSpace = getWidth() - getPaddingRight() - getPaddingLeft();
        } else {
            totalSpace = getHeight() - getPaddingTop() - getPaddingBottom();
        }
        int spanCount = Math.max(1, totalSpace / columnWidth);
        setSpanCount(spanCount);
        columnWidthChanged = false;
    }
    super.onLayoutChildren(recycler, state);
}

}

now you can set LayoutManager to recycle view

here i have set 250px

 AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 250);
 recycleView.setLayoutManager(layoutManager)

show the belove image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!