80

我想设置LayoutParams一个ImageView但似乎无法找到正确的方法。

我只能在 API 中找到ViewGroups各种ImageView. 然而ImageView似乎有这个功能。

此代码不起作用...

myImageView.setLayoutParams(new ImageView.LayoutParams(30,30));

我该怎么做?

4

4 回答 4

169

您需要设置 ImageView 所在的 ViewGroup 的 LayoutParams。例如,如果您的 ImageView 在 LinearLayout 内,则创建一个

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

这是因为 View 的父级需要知道分配给 View 的大小。

于 2010-06-03T12:18:51.993 回答
19

旧线程,但我现在遇到了同样的问题。如果有人遇到这个,他可能会找到这个答案:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

仅当您将 ImageView 作为子视图添加到 LinearLayout 时,这才有效。如果将其添加到 RelativeLayout,则需要调用:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
于 2012-05-21T15:10:10.940 回答
13

如果您正在更改现有 ImageView 的布局,您应该能够简单地获取当前的 LayoutParams,更改宽度/高度,然后将其设置回来:

android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);

我不知道这是否是您的目标,但如果是,这可能是最简单的解决方案。

于 2013-01-17T00:06:42.303 回答
6

An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view

Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'

The best way to do this:

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);
于 2013-02-20T18:22:15.780 回答