相对布局的百分比宽度

时间:2013-08-01 17:56:16

标签: android relativelayout

我有一个布局,我只想占用屏幕宽度的一定百分比(左边的图像)。现在,我的相对布局横跨显示器的整个宽度(右侧图像)。如何修复左边和右边的边距?

enter image description here

这是我定义相对布局的方式:

<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">

2 个答案:

答案 0 :(得分:6)

这个you can use LinearLayout with weightSum and layout_wright property

请尝试使用代码

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

答案 1 :(得分:1)

使用新的百分比支持库。

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

使用PercentageRelativelayout可以做到这一点。见下面的例子。

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

了解更多信息Android Doc

*例如&amp;教程* Tutorial1 Tutorial2 Tutorial3