-1

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

img.getLayoutParams().width = 100;

but the app crashes if I do that.

Henry
  • 42,982
  • 7
  • 68
  • 84
NilsPMC
  • 3
  • 4
  • Possible duplicate of [Set ImageView width and height programmatically?](https://stackoverflow.com/questions/3144940/set-imageview-width-and-height-programmatically). please add your stacktrace here. If you're setting the width after the layout has already been 'laid out', then make sure you also add `img.requestLayout()`. – S.R Jun 18 '17 at 11:09
  • Stacktrace: http://textuploader.com/d0gvw The img.requestLayout(); is not working.... – NilsPMC Jun 18 '17 at 11:33
  • your `img` is null.Show the `img` in xml if you've defined it there .and show how you get the view of it. – S.R Jun 18 '17 at 13:27

1 Answers1

2

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)

Advait Saravade
  • 3,029
  • 29
  • 34