以编程方式设置图像视图的匹配父级高度

我需要设置一个 图像视图的高度作为 匹配的父母编程。如果它是一个固定的高度,我知道如何设置。

但是我怎么才能把它设置为匹配的父母呢?

编辑:

实际上父布局的高度是动态的。所以我需要把图像视图的高度作为父布局的高度。

128952 次浏览
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

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

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.

initiate LayoutParams .

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

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));
imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

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

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.