0

I have the following XML for an ImageView:

    <ImageView
        android:id="@+id/iv"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:src="@drawable/crossy"
        android:scaleType="fitXY" />

When I run the following code:

iv = (ImageView) findViewById(R.id.iv);
Log.i("IV WxH", ""+iv.getWidth() + " " + iv.getHeight());

LogCat shows the following:

02-05 23:56:04.116: I/IV WxH(10211): 24 24

How do I ensure the height and width stays the same in code as it is in XML?

Si8
  • 9,141
  • 22
  • 109
  • 221

2 Answers2

5

The dp in your XML file indicates a measurement unit of "density independent pixels", while the value logged from your Java code is telling you the measurement in actual pixels.

px = dp * (dpi / 160)

So in this case, you have a 320 dpi screen, so every 1 density independent pixels is 2 physical pixels.

If you want the measurement in physical pixels, replace dp with px in your XML file. However, realize that on a device with lower dpi, your Imageview will take up a larger portion of the screen.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • This is right. If you want actual pixels, use px. But that probably won't give you the result you want across devices. – Gabe Sechan Feb 06 '14 at 05:04
  • How do I go around the issue? It's needed for an app I am creating. – Si8 Feb 06 '14 at 05:06
  • I want it to be same across devices – Si8 Feb 06 '14 at 05:10
  • I updated the answer... but I can't actually imagine that doing this is what you actually need to do... if you want it take up the same percentage of the screen on all devices, you need to use dp. – nhgrif Feb 06 '14 at 05:10
  • Thank you. I am creating a color picker which the user can drag inside a layout and now I see why the crosshair keeps going out of the layout, it's because of DP and PX difference – Si8 Feb 06 '14 at 05:11
3

View.getWidth() and View.getHeight() return in px so convert to dp

     dp = px / (dpi / 160);

    int width=View.getWidth();

    int widthdp=width/160;

dpi varies for different screens so check dpi for the MultipleScreen

compare this dp with your xml value.

Nambi
  • 11,944
  • 3
  • 37
  • 49