Imagine I have the following elements in a 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>
As a result it is only shown the black view (view2) because it is above (graphically, not in the xml) the blue view(view1)
Now my question is, do I need to specify which element is above another element with some attribute or it is already specified by putting one element below another in the xml?
I mean I have seen that if element 1 is below element 2 in the xml file, then, element 1 is actually above element 2 although element 1 is below element 2 in the xml file and that is a little confusing...
CodePudding user response:
Let's create a function that gives us to child views of the given view, paste below code to your fragment:
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
}
Now give our ConstraintLayout
an id:
android:id="@ id/cl_parent"
And use our function on this parent to get it's children. Then loop through it and paste view names into Log
You can paste below to your onViewCreated
or elsewhere:
If you want to use elevations, just add something like android:elevation="1dp"
to your first view and android:elevation="2dp"
for your second view in xml file:
for (childView in cl_parent.getAllChildren()) {
val fullName = resources.getResourceName(childView.id)
val elevationValue = childView.elevation.toString()
Log.e("childView", "$fullName $elevationValue")
}
This will give you view names and elevations of them. The higher value will be on top and visible to user. In your case: Output:
:id/view1 2.75
:id/view2 5.5