我想设置相对布局来包装内容,并将所有子项右对齐,这里是 xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000">
<TextView
android:id="@+id/textViewMsgDate"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="right"
android:layout_marginRight="8dp"
android:gravity="center"
android:textColor="#ffff"
android:text="simple"
/>
</RelativeLayout>
但正如您在图片中看到的,我没有成功?尽管如果我按预期对齐左侧 wrap_content 工作。
最佳答案
这里的问题是您将 RelativeLayout 的子项与其父项的 (RelativeLayout) 对齐,因为 RelativeLayout 的宽度设置为 wrap_content 这不会移动子项。
如果您不想让子元素在父元素的右侧对齐,那么父元素的宽度应该大于它的子元素。因此,要么给 RelativeLayout 一些宽度,要么使其成为“match_parent”,或者将 RelativeLayout 本身右对齐,以便其子项 (TextView) 随之移动。
注意:如果您向左对齐并使 RelativeLayout 宽度为“wrap_content”,它的行为与您预期的一样,因为 RelativeLayout 已经向左对齐,因此它也是子布局。
已编辑
要实现你想要的,只需这样做:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout18"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:id="@+id/textview_wrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000">
<TextView
android:id="@+id/textViewMsgDate"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginRight="8dp"
android:textColor="#ffff"
android:text="simple"
/>
</RelativeLayout></RelativeLayout>
结果应该是这样的:
关于android - relativeLayout 设置为 wrap_content 与 alignParentRight?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32485553/