5

If I want to set the width/height of an ImageView programmatically in Java, like this:

image_view.getLayoutParams().width = 200;

What's the unit of those "200"? Is it px/dp?
Does it look "the same" on every device? (That means: Is it extremely big on tablets and totally small on smartphones?)

Tobias Baumeister
  • 2,107
  • 3
  • 21
  • 36

2 Answers2

3

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

So, in your code you can write a swicth case and based on screen resolution which you can get from device metrices, can set the value accordingly like this:

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

Also you can change px values to dp using formula:

px = dp * (dpi/160)

Sushil
  • 8,250
  • 3
  • 39
  • 71
2

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

Fairly sure it's pixels.

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

Damian
  • 161
  • 1
  • 8