scientiffic
scientiffic

Reputation: 9415

Percentage width for a relative layout

I have a layout that I'd like to take up only a percentage of the screen's width (image on the left). Right now, my relative layout is spanning the entire width of the display (image on the right). How can I fix it to have margins on the left and right?

enter image description here

This is how I've defined my relative layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:background="@color/white"
    android:orientation="vertical" 
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp">

Upvotes: 2

Views: 9440

Answers (2)

Magesh Pandian
Magesh Pandian

Reputation: 9409

Use new percentage support library.

compile 'com.android.support:percent:24.0.0'

Using PercentageRelativelayout you can done this. See below example.

    <android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical"
    android:background="@android:color/black"
    android:orientation="vertical"
    app:layout_marginLeftPercent="5%"
    app:layout_marginRightPercent="5%"
    app:layout_marginTopPercent="5%"
    app:layout_marginBottomPercent="5%"
    >
</RelativeLayout>

For more Info Android Doc

*For Example & Tutorial * Tutorial1 Tutorial2 Tutorial3

Upvotes: 1

Tarsem Singh
Tarsem Singh

Reputation: 14199

for this you can use LinearLayout with weightSum and layout_wright property

so try following code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="8" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <!-- 1/8 % of Screen to left of your RelativeLayour -->
    </LinearLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="6"
        android:background="@color/white"
        android:orientation="vertical" >
    </RelativeLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <!-- 1/8 % of Screen to right of your RelativeLayour -->

    </LinearLayout>

</LinearLayout>

Upvotes: 6

Related Questions