[英]How to align view relative to multiple views in RelativeLayout?
我有一個父RelativeLayout和3個子視圖。 視圖一和視圖二是對齊父底。 我希望如果視圖一可見,則視圖三在視圖一上方對齊;否則,如果視圖一不可見,則在視圖二上方對齊。
這是我的布局:
<?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"
xmlns:tools="http://schemas.android.com/tools">
<View
android:id="@+id/one"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:background="@color/green"
tools:visibility="visible"/>
<View
android:id="@+id/two"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:background="@color/red"/>
<View
android:id="@+id/three"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_above="@id/one"
android:layout_marginBottom="10dp"
android:background="@color/yellow"/>
</RelativeLayout>
我知道如果我將一個視圖和第二個視圖放到另一層中,並將視圖三對齊到另一層之上,它將起作用,但是就目前的體系結構而言,我不允許這樣做。 還有其他方法可以做到這一點嗎? ConstraintLayout能夠解決此問題嗎?
嘗試這個:
<?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"
xmlns:tools="http://schemas.android.com/tools">
<View
android:id="@+id/one"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_above="@+id/two"
android:background="@android:color/holo_green_dark"
tools:visibility="visible"/>
<View
android:id="@+id/two"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:background="@android:color/holo_red_dark"/>
<View
android:id="@+id/three"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_above="@+id/one"
android:layout_marginBottom="10dp"
android:background="@android:color/holo_blue_bright"/>
</RelativeLayout>
事情是你只添加
android:layout_above="@+id/two"
查看一個將使其停留在第二個視圖上方並添加
android:layout_above="@+id/one"
查看三個將使其停留在視圖一之上。
因此,如果視圖一消失了,視圖三將停留在視圖二之上。
您可以通過將可見性設置為視圖一來進行測試。
ConstraintLayout能夠解決此問題嗎?
是。
我們可以通過編程來實現。
查找以下代碼,以根據第一個視圖的可見性狀態對齊第三個視圖。
final View view3 = findViewById(R.id.three);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
params.addRule(RelativeLayout.ABOVE, view3.getVisibility() == View.VISIBLE ? R.id.one : R.id.two);
view3.setLayoutParams(params);
如果要使用當前的版式,則可以通過編程將視圖的高度設置為零,而不用更改其可見性。 在這種情況下,視圖3保持在一個視圖的頂部,並且由於高度為零,因此視圖3將出現在視圖2的頂部。
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.one);
relativeLayout.getLayoutParams().height = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.