想象一下,我在 ConstraintLayout 中有以下元素:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@ id/view1"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/blue"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<View
android:id="@ id/view2"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
結果它只顯示黑色視圖(view2),因為它在藍色視圖(view1)上方(以圖形方式,不在xml中)
現在我的問題是,我是否需要指定哪個元素在具有某些屬性的另一個元素之上,或者它已經通過在 xml 中將一個元素放在另一個元素之下來指定?
我的意思是我已經看到,如果元素 1 在 xml 檔案中低于元素 2,那么元素 1 實際上在元素 2 之上,盡管元素 1 在 xml 檔案中低于元素 2,這有點令人困惑......
uj5u.com熱心網友回復:
讓我們創建一個函式,為我們提供給定視圖的子視圖,將以下代碼粘貼到您的片段中:
private fun View.getAllChildren(): List<View> {
val result = ArrayList<View>()
if (this !is ViewGroup) {
result.add(this)
} else {
for (index in 0 until this.childCount) {
val child = this.getChildAt(index)
result.addAll(child.getAllChildren())
}
}
return result
}
現在給我們ConstraintLayout一個id:
android:id="@ id/cl_parent"
并在這個父級上使用我們的函式來獲取它的子級。然后回圈遍歷它并將視圖名稱粘貼到Log您可以在下面粘貼到您的onViewCreated或其他地方:
如果您想使用高程,只需android:elevation="1dp"在您的第一個視圖和android:elevation="2dp"xml 檔案中的第二個視圖中添加類似的內容:
for (childView in cl_parent.getAllChildren()) {
val fullName = resources.getResourceName(childView.id)
val elevationValue = childView.elevation.toString()
Log.e("childView", "$fullName $elevationValue")
}
這將為您提供它們的視圖名稱和高度。較高的值將位于頂部并對用戶可見。在您的情況下:輸出:
:id/view1 2.75
:id/view2 5.5
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531627.html
標籤:安卓xml安卓布局布局
