Search code examples
androidandroid-layoutpositionpercentagepixel

Android - Position Views Based on Percentages instead of Pixels


Is it possible to arrange the XML-based position of a TextView or related element based upon percentages of screen width and height rather than pixels? For example, could

android:layout-marginLeft="150dip" 

be replaced with something like

android:layout-marginLeft="25%"? 

If not, is it possible to do so programmatically?


Solution

  • The layout_margin attributes do not accept a percentage value.

    You are looking for the LinearLayout attribute android:layout_weight which allows you to use percentages to define your layout:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight=".25" />
    
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight=".75" />
    
    </LinearLayout>
    

    In this example, the left TextView uses 25% of the screen and the right TextView 75%.