How do you setLayoutParams() for an ImageView?

前端 未结 4 1532
梦谈多话
梦谈多话 2020-11-27 15:53

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

相关标签:
4条回答
  • 2020-11-27 16:17

    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);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-27 16:36

    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.

    0 讨论(0)
  • 2020-11-27 16:41

    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.

    0 讨论(0)
提交回复
热议问题