Andrea Romagnoli Andrea Romagnoli - 1 year ago 111
Android Question

ImageView be a square with dynamic width?

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.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, 300));

I'm doing it inside an adapter.

Answer Source

The best option is to subclass ImageView yourself, overriding the measure pass:

public class SquareImageView  extends ImageView {


  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int width = getMeasuredWidth();
    setMeasuredDimension(width, width);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download