6

I am specifying a button's width as 600dp in values/dimens.xml, but when I deploy and run it on my Nexus 5 it takes up all the available width in the landscape orientation.

My activity only runs in landscape mode, as I have specified in manifest file. The layouts are in the layouts directory. The images are in the 'drawable-xxhdpi' directory and they appear fine, but everything that I specify in dp is magnified.

The previews in Android Studio and the actual device seem to behave as they have 600dp max width when it should be 1920. Why is this, and how can I fix it?

APerson
  • 8,140
  • 8
  • 35
  • 49

1 Answers1

7

The physical width of the display on a landscape Nexus 5 is 1920 pixels, However, 600dp != 600px. The Nexus 5 has a display density of ~445 ppi. A dp is pixels only at medium density (160 ppi). Thus, everything specified in dp will be scaled by a factor of about 445/160 = 2.78125. So 600dp is actually about 1669 pixels. That should account for most of what you're seeing.

There may also be something about your layout that is stretching the button. If you post your layout xml, we might be able to provide more info.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Ah, right. So I have to divide every dimension by that factor before setting in dimens.xml given I have the design in 1920x1080? Hmmm... so why is there need to have different dimens.xml files under values-swXXXXdp directories when `dp` is already doing this magic, I wonder? – user4092233 Sep 29 '14 at 19:07
  • @user4092233 Please refer to http://developer.android.com/training/multiscreen/index.html for details – Alexander Zhak Sep 29 '14 at 19:24
  • @user4092233 - I rarely use different dimens.xml files for different configurations, although they have their uses. For instance, you might want different dimensions for different screen sizes. On a large screen, for example, you might want a 1/2 inch margin around a view. So regardless of the pixel density, you could specify a margin of 80dp (which would be 80 pixels on an mdpi device, but more like 223 pixels on a Nexus 5). On a smaller screen, you might want only a 1/8 inch margin, which would be 20dp. For density-independent dimensions, use `/res/values-nodpi/dimens.xml` and px, not dp. – Ted Hopp Sep 29 '14 at 20:20