I have a GridView with ImageViews inside. I have 3 of them for each row. I can set correctly the width with WRAP_CONTENT and scaleType = CENTER_CROP, but I don't know how to set the ImageView's size to be a square. Here's what I did until now, it seems to be ok except the height, that is "static":
imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, 300));
I'm doing it inside an adapter.
For those looking for a Kotlin solution:
if someone wants the view to be not square, but proportionally resized in height (for example, 16/9 or 1/3), you can do it like this:
The best option is to subclass
ImageView
yourself, overriding the measure pass:Even more simple:
An squareImageView by specified width:
An squareImageView by specified height:
An squareImageView by minimum of dimentions:
The other answer works fine. This is just an extension of bertucci's solution to make an ImageView with square width and height with respect to xml inflated layout.
Create a class, say a SquareImageView extending ImageView like this,
Now, in your xml do this,
If you need an ImageView not to be dynamically created in program, instead, to be fixed in xml, then this implementation will be helpful.