3

我想设置相对布局来包装内容,并将所有子项向右对齐,这里是 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 按预期工作。

4

1 回答 1

2

这里的问题是您将 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>

结果应该是这样的:

输出

于 2015-09-09T17:29:37.487 回答