Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid numbers in Android layouts?

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?

like image 964
Msp Avatar asked Jul 06 '26 18:07

Msp


2 Answers

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>
like image 71
Floern Avatar answered Jul 10 '26 09:07

Floern


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.

like image 43
miensol Avatar answered Jul 10 '26 09:07

miensol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!