dp
depends on the device display metrics and won't work on all devices without a set of density-specific overlays, however, px
can be used instead.
Unfortunately, the simple rounding technique used by TypedValue#complexToDimensionPixelSize()
only considers non-negative values:
final int res = (int)(f+0.5f);
if (res != 0) return res;
if (value == 0) return 0;
if (value > 0) return 1;
return -1;
When f (the px value) is negative, the result is usually rounded incorrectly because it always uses addition. The following pixel sizes are observed for negative px
dimensions:
0px = 0.0
-1px = -1.0
-2px = -1.0
-3px = -2.0
-4px = -3.0
-5px = -4.0
...
I opened an AOSP issue for this method:
TypedValue#complexToDimensionPixelSize() rounds negative dimensions incorrectly
Considering this behavior, the following values will work on all devices:
<dimen name="match_parent">-2px</dimen>
<dimen name="wrap_content">-3px</dimen>
You can use -1px or -2px for match_parent, but wrap_content must be -3px. Either combination works on devices and emulators.
In practice, I've found that IntelliJ's Preview feature fails to render layouts when -1px is used for match_parent, and incorrectly renders -2px as if it were "wrap_content" when referenced by another dimension e.g. <dimen name="my_width">@dimen/match_parent</dimen>
. I have opened an issue for IntelliJ IDEA:
Android Preview cannot render layout_width="-1px"