可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to set the LayoutParams
for an ImageView
but cant seem to find out the proper way to do it.
I can only find documentation in the API for the various ViewGroups
, but not an ImageView
. Yet the ImageView
seems to have this functionality.
This code doesn't work...
myImageView.setLayoutParams(new ImageView.LayoutParams(30,30));
How do I do it?
回答1:
You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30); yourImageView.setLayoutParams(layoutParams);
This is because it's the parent of the View that needs to know what size to allocate to the View.
回答2:
Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30); yourImageView.setLayoutParams(layoutParams);
This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30); yourImageView.setLayoutParams(layoutParams);
回答3:
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);
回答4:
If you're changing the layout of an existing ImageView, you should be able to simply get the current LayoutParams, change the width/height, and set it back:
android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams(); layoutParams.width = 30; layoutParams.height = 30; myImageView.setLayoutParams(layoutParams);
I don't know if that's your goal, but if it is, this is probably the easiest solution.