Menu Home

RelativeLayout居中显示

layout-2015-06-20-115951

XML方式

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    <TextView
        android:id="@+id/center"
        android:background="@android:color/holo_red_light"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerInParent="true"
        android:text="Center"
        android:gravity="center" />


    <TextView
        android:id="@+id/left"
        android:background="@android:color/background_dark"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_alignTop="@id/center"
        android:layout_toLeftOf="@id/center"
        android:text="Left"
        android:textColor="@android:color/white"
        android:gravity="center"
        />


    <TextView
        android:id="@+id/right"
        android:background="@android:color/holo_purple"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_alignTop="@id/center"
        android:layout_toRightOf="@id/center"
        android:text="Right"
        android:textColor="@android:color/white"
        android:gravity="center"
        />
</RelativeLayout>

Java方式

centerLayoutParam.addRule(RelativeLayout.CENTER_IN_PARENT);//把center TextView居中显示

leftLayoutParam.addRule(RelativeLayout.LEFT_OF, R.id.one);//把left TextView控件放在center TextView左侧显示,并且距离center TextView为50px
((MarginLayoutParams) LayoutParam).rightMargin = 50;

...

这种方法的好处是可以把某一个控件先居中显示,然后再根据相对位置来摆放其他控件。

Categories: android应用 未分类

Tagged as:

lnmcc

Leave a Reply

Your email address will not be published.