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 achievin
If you provide a fixed column width, you can extend RecyclerView
and set the span count in onMeasure
accordingly:
public AutofitRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
// Read android:columnWidth from xml
int[] attrsArray = {
android.R.attr.columnWidth
};
TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
columnWidth = array.getDimensionPixelSize(0, -1);
array.recycle();
}
manager = new GridLayoutManager(getContext(), 1);
setLayoutManager(manager);
}
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
if (columnWidth > 0) {
int spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
manager.setSpanCount(spanCount);
}
}
See my blog post for more info: http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html