I have a RecyclerView with a GridLayoutManager that displays Card Views. I want the cards to rearrange according to the screen size (the Google Play app does this kind of th
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;
}
A simple Kotlin extension function. Pass the width in DP (same as the overall width in the item xml)
/**
* @param columnWidth - in dp
*/
fun RecyclerView.autoFitColumns(columnWidth: Int) {
val displayMetrics = this.context.resources.displayMetrics
val noOfColumns = ((displayMetrics.widthPixels / displayMetrics.density) / columnWidth).toInt()
this.layoutManager = GridLayoutManager(this.context, noOfColumns)
}
Call it like every other extension...
myRecyclerView.autoFitColumns(200)