I have a fragment that has a CoordinatorLayout
type of the main layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/secondContainer"
android:layout_height="match_parent"
android:layout_width="match_parent"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"/>
<include
android:id="@+id/mainContainer"
layout="@layout/view_home_content"
app:layout_anchorGravity="bottom"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
So inside the main container I got two included separate layouts. First one
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/topContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/topButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
And the bottom one
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/bottomContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/bottomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
So my main goal is to make view with id topButton
constraint to bottom of bottomText
. I was trying to make it programmatically and it works fine if they are In the same xml file but when they are separate as I show above it doesn't work
Here is how I programmatically connects them
with(binding.topContainer) {
topContainer = topContainer
button = topButton
}
with(binding.bottomContainer) {
text = bottomText
}
val mConstraintSet = ConstraintSet()
mConstraintSet.clone(topContainer)
mConstraintSet.clear(R.id.topButton, ConstraintSet.TOP)
mConstraintSet.connect(R.id.topButton, ConstraintSet.TOP, R.id.bottomText, ConstraintSet.BOTTOM)
mConstraintSet.applyTo(topContainer)
As I said earlier it works if I use ID's of layouts from one file. But this way seems they don't see each other
It's expected that It won't work when using the two separate files. To use constraints, you need to put the desired views inside the same constraint layout. You have a ConstraintLayout for bottom and another for top. You can try to put a ConstraintLayout inside your coordinatorLayout and try to put the constraints in include tags.