【发布时间】:2011-02-27 06:48:04
【问题描述】:
我想将LayoutParams 设置为ImageView,但似乎找不到正确的方法。
我只能在 API 中找到各种 ViewGroups 的文档,而不是 ImageView。然而ImageView 似乎有这个功能。
此代码不起作用...
myImageView.setLayoutParams(new ImageView.LayoutParams(30,30));
我该怎么做?
【问题讨论】:
我想将LayoutParams 设置为ImageView,但似乎找不到正确的方法。
我只能在 API 中找到各种 ViewGroups 的文档,而不是 ImageView。然而ImageView 似乎有这个功能。
此代码不起作用...
myImageView.setLayoutParams(new ImageView.LayoutParams(30,30));
我该怎么做?
【问题讨论】:
您需要设置 ImageView 所在的 ViewGroup 的 LayoutParams。例如,如果您的 ImageView 在 LinearLayout 中,那么您创建一个
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
这是因为 View 的父级需要知道分配给 View 的大小。
【讨论】:
TypedValue.applyDimension(TypedValue.ComplexUnit_DP, 30, getResources().getDisplayMetrics()) 之类的东西将像素转换为 DP
旧线程,但我现在遇到了同样的问题。如果有人遇到这个,他可能会找到这个答案:
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);
【讨论】:
如果您要更改现有 ImageView 的布局,您应该能够简单地获取当前的 LayoutParams,更改宽度/高度,然后将其重新设置:
android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);
我不知道这是否是您的目标,但如果是,这可能是最简单的解决方案。
【讨论】:
myImageView.setLayoutParams(layoutParams); 再次分配 LayoutParams ?由于您修改了对 LayoutParams 的引用,因此不应该这样做。
ImageView 从使用 ViewGroup.LayoutParams 的 View 获取 setLayoutParams。如果你使用它,它在大多数情况下会崩溃,所以你应该使用 View.class 中的 getLayoutParams()。这将继承 ImageView 的父视图并始终有效。你可以在这里确认:ImageView extends view
假设您将 ImageView 定义为 'image_view' 并将宽度/高度 int 定义为 'thumb_size'
最好的方法:
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);
【讨论】: