Android: Set ImageView layout_height programmatically

后端 未结 2 1122
萌比男神i
萌比男神i 2020-12-24 07:38

I have an ImageView in my main.xml file:



        
2条回答
  •  無奈伤痛
    2020-12-24 08:05

    You can do something like this:

    LinearLayout.LayoutParams layoutParams  = new LinearLayout.LayoutParams(width_physical_pixels, height_physical_pixels);
    imageView.setLayoutParams(layoutParams);
    

    But in the parameters it takes a pixel, so you would have to use the formula to convert pixels to dp, for example you can use this to convert:

    float scale = getBaseContext().getResources().getDisplayMetrics().density;    
    px = dp_that_you_want * (scale / 160);
    

    Putting everything together:

    //Get screen density to use in the formula.
    float scale = getBaseContext().getResources().getDisplayMetrics().density;    
    px = dp_that_you_want * (scale / 160);
    
    LinearLayout.LayoutParams layoutParams  = new LinearLayout.LayoutParams(px, px);
    imageView.setLayoutParams(layoutParams);
    

    I don't know if this is what you are looking for, or if it will work, so let me know if it does.

提交回复
热议问题