layout_alignParentEnd里面的layout_alignParentEnd没有按预期工作

时间:2018-01-23 15:17:10

标签: android android-relativelayout

假设我们将视图结束对齐的场景,我们需要一个视图内部的视图也结束对齐。我在其中使用了layout_alignParentEnd,但它扩展了match_parent之类的第一个视图,尽管它是wrap_content

代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<RelativeLayout
    android:id="@+id/zone_controls"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:background="@color/primary_dark">

    <ImageButton
        android:id="@+id/btn_more_options"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:background="?android:selectableItemBackground"
        android:padding="12dp"
        android:src="@mipmap/ic_more_options" />

</RelativeLayout>

预期:

enter image description here

我明白了:

enter image description here

2 个答案:

答案 0 :(得分:0)

删除android:layout_alignParentEnd="true"中的ImageButton,因为它的父级已经结束了对齐:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<RelativeLayout
    android:id="@+id/zone_controls"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:background="@color/primary_dark">

    <ImageButton
        android:id="@+id/btn_more_options"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?android:selectableItemBackground"
        android:padding="12dp"
        android:src="@mipmap/ic_more_options" />

</RelativeLayout>

答案 1 :(得分:0)

添加线性布局,因为您已将align设置为以相对布局结束。

试试这个

<?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="wrap_content">

<RelativeLayout
    android:id="@+id/zone_controls"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:background="@color/colorPrimary"
    >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

       <!-- add more views here -->

        <ImageButton
            android:id="@+id/btn_more_options"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?android:selectableItemBackground"
            android:padding="12dp"
            android:src="@drawable/ic_launcher_background"
            />

    </LinearLayout>

</RelativeLayout>

</RelativeLayout>

注意:您的观点在linearlayout中从右到左对齐。