难以理解layout_alignWithParentIfMissing

时间:2013-05-23 07:35:17

标签: android android-layout

我不理解layout_alignWithParentIfMissing属性TextView的含义。

我阅读了以下documentation

android:layout_alignWithParentIfMissing

如果设置为true,则无法在layout_toLeftOflayout_toRightOf等找到锚点时将父项用作锚点。

必须是布尔值,truefalse

请向我解释。

3 个答案:

答案 0 :(得分:26)

这仅适用于使用RelativeLayout。

如果将element设置为toLeftOf,则表示它将位于此元素的左侧。

但是如果缺少这个元素,因为你删除了它,例如它将与父元素对齐。

以此为例

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="102dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignWithParentIfMissing="true"
        android:layout_alignBottom="@+id/textView1"
        android:layout_toRightOf="@+id/textView1"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

看看会发生什么情况如果删除textView1但不要触摸textView2。

它将向左下方(不正确,因为它在父级内部)

Android会将元素相对于父元素而不是元素定位,因为它缺失了。

如果是假,则忽略与缺失元素相关的参数。

答案 1 :(得分:2)

另一个样本。我刚刚用过。

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

    <Button
       android:id="@+id/streamOverflow"
       android:layout_width="50dp"
       android:layout_height="30dp"
       android:layout_alignParentRight="true"
       android:background="@drawable/ic_action_overflow"
       android:focusable="false" />

    <TextView
       android:id="@+id/delete_time"
       style="?android:attr/textAppearanceSmall"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Disappears "
       android:layout_toLeftOf="@id/streamOverflow"
       android:layout_alignWithParentIfMissing="true"
     />
</RelativeLayout>

如果缺少“streamOverflow”,“delete_time”textview的行为就像拥有android:layout_alignParentRight =“true”属性。

答案 2 :(得分:0)

在“相对布局”中,可以相对于另一个视图指定视图的位置。

标记 layout_toLeftOf layout_toRightOf 将视图相对于“锚点”视图对象定位。如果缺少此锚点视图,标记 alignWithParentIfMissing 将使您的视图与父视图对齐。