I try to make a grid-layout with square images. I thought that it must be possible to manipulate the GridLayoutManager
by manipulating onMeasure
to do a
super.onMeasure(recycler, state, widthSpec, widthSpec);
instead of
super.onMeasure(recycler, state, widthSpec, heightSpec);
but unfortunately, that didn't work.
Any ideas?
Once again, I recommend the relatively recent 'percent' layouts. Using the dependency
'com.android.support:percent:25.2.0'
, you can do something like this:It's probably much faster than ConstraintLayout, though someday we probably won't care anymore.
In case someone would like to scale the view differently - this is how you do it:
To have the square elements in my RecyclerView, I provide a simple wrapper for my root View element; I use the following
SquareRelativeLayout
in place ofRelativeLayout
.Then, in my XML layout for the adapter, I've just referenced the custom view as shown in the following. Though, you can do this programmatically also.
Note: Depending on which orientation your grid is, then you may want to have the width based off of height (
GridLayoutManager.HORIZONTAL
) instead of the height being based off the width (GridLayoutManager.VERTICAL
).Starting API 26 (Support Library 26.0), one can use ConstraintLayout that exposes aspect ratio property to force views to be squared: https://developer.android.com/training/constraint-layout/index.htm
Example of layout I'm using in GridLayoutManager:
app:layout_constraintDimensionRatio="h,1:1"
is the key attribute hereConstraint layout solves this problem. Use
app:layout_constraintDimensionRatio="H,1:1"
recyclerview_grid_layout.xml
I don't like chosen answer so let me provide mine: Instead of wrapping entire item layout in SomeDammyLayoutWithFixedAspectRatio you can hack GridLayoutManager and rewrite code inside measureChild. I've replaced these lines:
to:
It seems to work fine.
Don't get me wrong, this is quite messy too, but at least this solution doesn't hurt app performance by extending view hierarchy