Set ImageView width and height programmatically?
⚡TLDR
Changing the dimensions of an ImageView in Android programmatically is a breeze with the LayoutParams tool. All you need to do is set up a new LayoutParams with the desired width and height, and assign it to your ImageView.
Here's a quick look at how to do it:
For LinearLayout:
For RelativeLayout:
Change pixel values as required or use WRAP_CONTENT and MATCH_PARENT to fit the ImageView neatly within its parent.
Debugging dynamic Initialization and Layouts
Working with dynamic image views or varying layouts? Here are some handy instructions:
- Dynamic ImageView creation:
- Responsive to the screen size:
Let's convert dp units to pixels, using
TypedValueandDisplayMetrics:
Dodge the exceptions and optimize
Fear that haunting ClassCastException? An accurate case of LayoutParams can help:
Responsive sizing, the smart way
- Matching parent size:
Got an
ImageViewthat needs to take up all available space? UseMATCH_PARENT:
- No stretch, just fit:
Want the
ImageViewto just cover its content without stretching? Here's the trick:
Linked
Linked
Was this article helpful?