Search code examples
androiduser-interfaceimageviewandroid-imageviewui-design

Android UI design automatic ImageView re-size


An ImageView gets an image and wraps the content so if the image has dimensions like 100x100, the ImageView has the same dimensions. I want to specify only the layout_height of this ImageView and when it matches the image to re-size properly the layout_width of the ImageView.

Here is an example:

image size = 100x100;

ImageView's layout_height = 200;

ImageView's layout_width should become 200 not 100.

Is this possible?


Solution

  • You'd need to create a custom ImageView and override onMeasure to make the view always square.

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
        SQUARE_DIMENSION  = this.getMeasuredHeight(); // whatever height you want here
    
        this.setMeasuredDimension(SQUARE_DIMENSION, SQUARE_DIMENSION);
    }