Search code examples
androidimageviewlayoutparams

How do you change the size of an ImageView?


I have setup my ImageView like the following:

    <ImageView android:id="@+id/dl_image"
               android:layout_width="60dp"
               android:background="@drawable/pictureframe"
               android:layout_height="wrap_content"
               android:layout_marginRight="10dp"
               android:layout_alignParentLeft="true"
               android:layout_centerVertical="true"
               android:adjustViewBounds="true"
               android:scaleType="fitCenter"/>

Notice that layout_width is fixed to 60dp. Depending on the content that I acquired online, I want to resize this width to 90dp, or 120dp (while maintaining the aspect ratio of the image).

I tried using setLayoutParams, but passing LayoutParams(120, LayoutParams.WRAP_CONTENT) throws an exception. It doesn't seem to like it.

If possible, I am trying to avoid making another ImageView for larger sizes.


Solution

  • If you're working with an existing view it can be a lot of work creating a new set of LayoutParams from scratch. Instead - you can grab the view's existing LayoutParams, edit these, and then apply them to the view to update its LayoutParams using setLayoutParams()

    ImageView imageView = findViewById(R.id.dl_image);
    LayoutParams params = (LayoutParams) imageView.getLayoutParams();
    params.width = 120;
    // existing height is ok as is, no need to edit it
    imageView.setLayoutParams(params);
    

    Make sure you import the correct type of LayoutParams. For this case, as you commented, you can just use the LayoutParams of a ViewGroup. If you were setting parameters specific to a certain type of view (e.g. alignments in RelativeLayouts) you would have to import the LayoutParams of that type of view.