Android布局中的一个元素相对于其他元素

时间:2014-04-02 22:55:56

标签: android android-layout margin

有没有办法在布局上放置一些被称为“主要”的元素,然后让另一个元素相对于那些元素居中?

想象一下,屏幕左侧和右侧有两个滑出菜单,然后是中间的内容部分,您希望它始终位于您拥有的任何空白区域的中心。

因此,如果它们都在外面,它位于中心,但如果你打开左边的那个,主要部分被推到右边,仍然位于屏幕上剩余空白区域的中心。

因此菜单部分是“主要的”,因为它们确定其余元素(即内容部分)的位置。

1 个答案:

答案 0 :(得分:0)

所以我想我已经想出办法来做到这一点:

  1. 将整件事包裹在RelativeLayout
  2. 将主要的那些放在那里
  3. 创建辅助RelativeLayout并将其设为“toRightOf”或“toLeftOf”,并将其设置为fill_parent,其高度和宽度均为零边距
  4. 将您想要的内容放在最后创建的RelativeLayout中的另一个相对或线性布局中,并将其设置为centerInParent
  5. E Voila!
  6. 示例:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="0dp" >
    
    <!-- this would contain the "content section" --> 
    <RelativeLayout 
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_toLeftOf="@+id/primaryObject" 
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        >
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true" 
            >
            <Button 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="testButton"
                />
    
        </LinearLayout>
    
    </RelativeLayout>
    
     <!-- this would be the primary thing -->
    <FrameLayout 
        android:id="@+id/primaryObject"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true" >
    
        <ImageButton
            android:id="@+id/menuPulloutButton"
            style="@android:style/Widget.Holo.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:src="@drawable/menu_sidebar_button" />
    </FrameLayout>
    
    </RelativeLayout>