MainActivity.kt
package com.cfsuman.kotlintutorials
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.constraintlayout.widget.ConstraintSet.*
class MainActivity : AppCompatActivity() {
private lateinit var context:MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get the context
context = this
// Get the widgets reference from XML layout
val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
val textView = findViewById<TextView>(R.id.textView)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val constraintSet = ConstraintSet()
constraintSet.clone(rootLayout)
// Remove text view top constraint
constraintSet.clear(
textView.id, // widget to remove constraint
TOP // the Anchor to remove constraint from
)
// Finally, apply the constraint set to layout
constraintSet.applyTo(rootLayout)
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
android:id="@+id/rootLayout"
android:background="#DCDCDC"
android:padding="24dp">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove TextView Top Constraint"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="#FEFEFA"
android:fontFamily="sans-serif"
android:padding="12dp"
android:text="Lorem ipsum dolor sit amet, consectetur
adipiscing elit."
android:textColor="#333399"
android:textSize="24sp"
android:textStyle="italic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>