Search code examples
androidandroid-resources

Wrong resource is used


I have two layouts for different screen size:

layout
layout-w580dp

Display metrics log for portrait and landscape orientation:

DisplayMetrics{density=1.3312501, width=800, height=1280, scaledDensity=1.5841876, xdpi=216.0, ydpi=216.0}
DisplayMetrics{density=1.3312501, width=1280, height=800, scaledDensity=1.5841876, xdpi=216.0, ydpi=216.0}

Potrait orientation has 800/1.5841876=504dp, so resource from layout folder sould be used. Landscape orientation has 1200/1.5841876=704dp, so resource from layout-w580dp folder sould be used.
However, in both orientation resource is obtained from layout-w580dp folder.
What causes that issue?


Solution

  • According to Supporting Multiple Screens the formula to convert from dp to physical pixels is px = dp * (dpi / 160). Since we want to convert in the opposite direction, we need to solve for dp: dp = px * 160 / dpi. For your two examples, we have the following values and calculation:

    1. px = 800 (width), dpi = 216 (xdpi) dp = px * 160 / dpi = 800 * 160 / 216 = 592.59.

    2. px = 1280 (width), dpi = 216 (xdpi) dp = px * 160 / dpi = 1280 * 160 / 216 = 948.15.

    In both cases, the width is more than 580 dp.