You can use the span based on calculating the width.
public class AutoFitGridLayoutManager extends GridLayoutManager {
private boolean columnWidthChanged = true;
Context context;
public AutoFitGridLayoutManager(Context context) {
super(context, 1);
this.context = context;
setColumnWidth();
}
public void setColumnWidth() {
columnWidthChanged = true;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (columnWidthChanged) {
//int spanCount = Math.max(1, totalSpace / columnWidth);
//setSpanCount(spanCount);
setSpanCount(Utils.calculateNoOfColumns(context));
columnWidthChanged = false;
}
super.onLayoutChildren(recycler, state);
}
}
For calculating the columns you can use this method:
public static int calculateNoOfColumns(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
int scalingFactor = 200; // You can vary the value held by the scalingFactor
// variable. The smaller it is the more no. of columns you can display, and the
// larger the value the less no. of columns will be calculated. It is the scaling
// factor to tweak to your needs.
int columnCount = (int) (dpWidth / scalingFactor);
return (columnCount>=2?columnCount:2); // if column no. is less than 2, we still display 2 columns
}