Question

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?

Was it helpful?

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%.

OTHER TIPS

Use the PercentRelativeLayout (http://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html)

<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.PercentFrameLayout>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top