在相对布局中调整视图在其他视图可见性上的位置?

Sar*_*glt 2 android android-layout

我可以仅使用 xml 执行此操作吗:

  1. 相对布局中的视图 A 在其可见时与某些视图 B 对齐。
  2. 当 View -B 消失时,相对布局中的 View-A 与某些 View-C 对齐?

考虑 C 在 B 之上,B 在 A 之上:

在此输入图像描述

Méd*_*ric 5

您不能直接在 xml 中执行此操作,但根据您的需要,您可以使用layout_alignWithParentIfMissing

例如,如果 View-A 与 View-B 左对齐且 View-B 可见性消失,则 View-A 将与其相对布局父级左对齐。

请参阅下一个示例:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/viewB"
        android:layout_width="20dp"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true" />

    <View
        android:id="@+id/viewA"
        android:layout_width="20dp"
        android:layout_height="match_parent"
        android:layout_toLeftOf="@id/viewB"
        android:layout_alignWithParentIfMissing="true" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

如果viewB可见,则viewB将位于RelativeLayout的右侧,而viewA将位于其左侧。如果viewB消失了,viewA将位于RelativeLayout的右侧。

没有这一行:

android:layout_alignWithParentIfMissing="true" />
Run Code Online (Sandbox Code Playgroud)

当viewB消失时,viewA将显示在RelativeLayout左侧...

对于您的示例,您只需将layout_toLeftOf属性替换为layout_above。

否则,您需要在活动(或片段,或任何地方......)中以编程方式更改视图 A 或视图 B 对齐方式