Is it possible to design an Android layout (LinearLayout or RelativeLayout) without specifying any dp, px or any other units? Maybe using percentages? layout_weight is an option. But still what about margins and paddings? Can we completely avoid magic numbers from a layout?
There is the Percent Support Library with its PercentFrameLayout and PercentRelativeLayout where you can specify any layout dimensions (i.e. size, position and margins) with percentages instead of absolute values:
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
app:layout_marginTopPercent="25%"
app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentRelativeLayout>
You can always define and use dimension variable to remove magic number from layouts i.e.:
<ImageView
layout_width="@dimen/large_photo_size"
layout_height="@dimen/large_photo_size"
/>
Where @dimen/large_photo_size is defined inside dimens.xml resource file i.e.:
<resources>
<dimen name="large_photo_size">25dp</dimen>
</resources>
Yet another alternative would be to extract width and height settings into styles i.e.:
<style name="Thumbnail">
<item name="android:layout_width">25dp</item>
<item name="android:layout_height">25dp</item>
</style>
and use it i.e. <ImageView style="@style/PopupMenu" ... />
With themes you can apply certain styles globally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With