a LayoutParams constructor overload with size in dip. Why not?

19 views
Skip to first unread message

Antonino Orlando

unread,
Jun 30, 2015, 9:46:29 AM6/30/15
to android-...@googlegroups.com

In Android SDK there isn't an overload of a constructor of ViewGroup (and subclasses) with possibilities to specify the width and height in DP (or DIP) instead of in pixel. Why? Actually we have:

ViewGroup.LayoutParams(int width, int height)

Could be a good idea to have:

ViewGroup.LayoutParams(int dpWidth, int dpHeight, int ComplexUnitType.Dip) 

where ComplexUnitType could be an enum with units of measurement (for e.g)

Dave Smith

unread,
Jul 1, 2015, 10:04:08 AM7/1/15
to android-...@googlegroups.com
Pretty much all of the Java graphics/layout APIs in Android work with raw pixel values (measure, layout, draw) consistently. The design intention (as I understand it) is that complex units are best defined in XML resources (layout.xml, dimens.xml, etc.). When pulling resources into your Java code, the methods on Resources (such as getDimensionPixelSize() for dimensions) will do the work of converting the complex type into pixels for that devices.

If you have a handful of raw dimensions you want to define explicitly for use in Java code, put them in a dimens.xml. That will allow you the flexibility to provide a separate value for the same resource on different device configurations. This is why Google prefers this pattern over you trying to construct a complex unit from a Java constant (which can't be controlled per device configuration) using something like TypedValue.applyDimension().

BTW, the complex type identifiers do already exist as constants on TypedValue:

Cheers,
--
Dave Smith, PE
@devunwired
Reply all
Reply to author
Forward
0 new messages