【问题标题】:Center One Element in Android Layout Relative to the Other ElementsAndroid 布局中的一个元素相对于其他元素居中
【发布时间】:2014-04-03 07:28:53
【问题描述】:
有没有办法让布局上的一些元素例如被称为“主要”,然后让另一个元素相对于这些元素居中?
想象一下,您在屏幕的左侧和右侧有两个滑出菜单,然后中间有一个内容部分,您希望始终位于您拥有的任何空白空间的中心。
所以如果它们都出来了,它就在中间,但是如果你打开左边的那个,主要部分就会被推到右边,仍然在屏幕上剩余的空白空间的中心。
因此,菜单部分是“主要的”,因为它们决定了其余元素(即内容部分)的位置。
【问题讨论】:
标签:
android
android-layout
margin
【解决方案1】:
所以我想我已经找到了一种方法来做到这一点:
- 将整个内容包装在一个相对布局中
- 把主要的放在那里
- 创建辅助 RelativeLayout 并将其设置为“toRightOf”或“toLeftOf”作为主要布局,并将其高度和宽度均设置为 fill_parent,且边距为零
- 在最后创建的 RelativeLayout 中将任何您想要的内容放在另一个相对或线性布局中,并将其置于 centerInParent
- 瞧瞧!
例子:
<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>