我有一个RelativeLayout
,其中有两个孩子,RelativeLayout
也包含几个按钮和东西。这些子布局不在我的主布局中居中,主布局确实包含了这两个方面的其他一些东西。我希望第一个在第二个之上。这很容易,只需在第二个中使用android:layout_below="@+id/firstLayout"
即可。但我也希望第二个在第一个的中心对齐。我的意思是我想要第二个布局找到第一个布局的中心,并对齐自己,使其中心位于相同的x位置。我看到alignLeft, alignRight, alignTop, and alignBaseline
,但没有中心。这是否可以在不必硬编码边距的情况下将第二种布局划分为某些?
这是我最终想要的一个粗略的例子,蓝色条将是第一个布局,红色框将是第二个布局。我知道我可以将它们包装在大小等于RelativeLayout
的另一个"wrap_content"
中,然后将centerHorizontal="true"
用于第二个{{1}}。但我真的宁愿把两个都留作我的主要布局的孩子(如果我让他们成为一个单独布局的孩子,我将不得不对我的应用程序的某些部分的工作方式进行一些更改。我试图避免这种情况。)
答案 0 :(得分:9)
如果您可以将父布局的宽度设置为“wrap_content”,则可以将两个子布局设置为居中
答案 1 :(得分:3)
有时您可以将alignLeft
和alignRight
设置为所需的视图,然后在要居中的元素上使用重力。
例如:
android:layout_below="@+id/firstLayout"
android:layout_alignLeft="@+id/firstLayout"
android:layout_aligntRight="@+id/firstLayout"
android:gravity="center"
如果该组件不是TextView
(或您不需要背景的视图),则可以将其包装在具有上述属性的FrameLayout
中。
<MyView id="@+id/firstLayout" .. other props/>
<FrameLayout
... other props
android:layout_below="@+id/firstLayout"
android:layout_alignLeft="@+id/firstLayout"
android:layout_aligntRight="@+id/firstLayout"
android:gravity="center" >
<MyView id="@+id/myAlignedView" ..other props />
</FrameLayout>
这样,底部视图将是一个宽度与上部相同的Frame,但在其中部将有一个以宽度为中心的视图。
当然,只有当您知道哪个是较大的视图时,这才有效。如果没有,正如Laranjeiro所回答的那样,将两个内容包裹在另一个具有重心的布局中。
答案 2 :(得分:1)
对我有用的唯一解决方案是将两个组件包装在FrameLayout中,使用更大组件的尺寸,并使用属性将第二个组件设置在FrameLayout的中心
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/red_component"
android:layout_width="100dp"
android:layout_height="100dp"/>
<View
android:id="@+id/blue_component"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center" />
</FrameLayout>
答案 3 :(得分:0)
对于我一直使用此f.e进行垂直居中对齐的文本:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_alignTop="@id/theBigOne"
android:layout_alignBottom="@id/theBigOne"
android:layout_toRightOf="@id/theBigOne"
答案 4 :(得分:-3)
设置如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/bottomHolder"
android:layout_alignParentTop="true"
android:layout_centerInParent = "true"/>
<View
android:id="@+id/bottomHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
</RelativeLayout>