106

I need to set the height of an imageview as matchparent programatically.if it is a fixed height i know how to set.

but how can i set it as matchparent?

EDIT:

actually height of the parent layout is dynamic.so i need to make the height of the imageview as the height of parent.

Cœur
  • 37,241
  • 25
  • 195
  • 267
andro-girl
  • 7,989
  • 22
  • 71
  • 94

8 Answers8

287
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
C. Leung
  • 6,218
  • 3
  • 20
  • 32
66
imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;
Luke Allison
  • 3,118
  • 3
  • 24
  • 40
  • 10
    If you're setting the params for the first time because you made the imageview programmatically, this will null pointer error (or does with text view) and should everywhere else. – Tatarize May 14 '18 at 08:23
15
imageView.setLayoutParams
    (new ViewGroup.MarginLayoutParams
        (width, ViewGroup.LayoutParams.MATCH_PARENT));

The Type of layout params depends on the parent view group. If you put the wrong one it will cause exception.

xandy
  • 27,357
  • 8
  • 59
  • 64
15

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

Muhamed Riyas M
  • 5,055
  • 3
  • 30
  • 31
8

I had same issue. Resolved by firstly setting :

imageView.setMinHeight(0);
imageView.setMinimumHeight(0);

And then :

imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

setMinHeight is defined by ImageView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.

fisio
  • 494
  • 6
  • 12
3

You can try this incase you would like to match parent. The dimensions arrangement is width and height inorder

web = new WebView(this);
        web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
1

You can use the MATCH_PARENT constant or its numeric value -1.

-20

initiate LayoutParams .

assign the parent's width and height and pass it to setLayoutParams method of the imageview

luckyluke
  • 642
  • 2
  • 7
  • 22
  • 3
    you should never pass the parents actual dimensions. Always use MATCH_PARENT instead of actual values. In general I wouldn't recommend using absolute sizes because it might look completely different on all the screens there are. I'd prefer using weights. – Daniel Bo Nov 28 '16 at 16:06
  • 18
    To be honest this should be a comment – Neon Warge Feb 26 '17 at 10:39