ImageView getLayoutParams width unit

If I want to set the width / height of the ImageView programmatically in Java, for example:

image_view.getLayoutParams().width = 200; 

What is the unit of these "200"? Is this px / dp?
Does it look โ€œthe sameโ€ on every device? (This means: is it extremely large on tablets and very small on smartphones?)

+4
source share
2 answers

http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html

Pretty sure these are pixels.

height, either MATCH_PARENT, WRAP_CONTENT, or a fixed size in pixels

+2
source

It is in pixels. But to be device independent, we need to set the value to dp.

So, in your code you can write a swicth case and based on the screen resolution that you can get from the device metrics, you can set the value accordingly as follows:

  DisplayMetrics metrics = this.getResources().getDisplayMetrics(); if(metrics.density == 1) // else if(metrics.density == 2) // else if(metrics.density == 1.5) // 

You can also change the px values โ€‹โ€‹to dp using the formula:

px = dp * (dpi / 160)

+2
source

Source: https://habr.com/ru/post/1498105/


All Articles