Android RelativeLayout alignCenter from another View
If you can set width of parent layout to "wrap_content" you could then put both children layouts to center
Sometimes you can set alignLeft
and alignRight
to the desired view and then use gravity on the element you want centered.
For example:
android:layout_below="@+id/firstLayout"android:layout_alignLeft="@+id/firstLayout"android:layout_aligntRight="@+id/firstLayout"android:gravity="center"
If the component is not a TextView
(or a view where you don't need the background) you could then wrap it in a FrameLayout
with the above properties.
<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>
This way, the bottom view will be a Frame with the same width as the upper one, but inside it there will be a view that is centered to the width.
Of course this only works when you know which is the larger view. If not, as Laranjeiro answered, wrap both contents in another layout with centered gravity.
For texts I have been using this f.e for a vertical-center alignment:
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"