简体   繁体   中英

Android resize imageview programmatically

Is it possible to resize an imageview in code? I tried:

img.getLayoutParams().width = 100;

but the app crashes if I do that.

Your app may be crashing because your ImageView may not have been dynamically generated (your stack trace link is a 404 so I can't verify).

In any case, to make the system redraw your ImageView you must call img.requestLayout() . However, calling requestLayout() is not guaranteed to result in an onDraw contrary to documentation, so in practice invalidate() is also called following the requestLayout()

Try this:

img.getLayoutParams().width = 100;
img.requestLayout();
img.invalidate();

EDIT:

The stack trace is now available. Looks like you're getting a NullPointerException when you try setting the ImageView's width. Are you sure your ImageView has been declared? If it has been declared then have you added it to your layout? An ImageView not added to the layout will return null when trying to access it's LayoutParams (because it's not a part of the layout yet)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM