Friday, February 28, 2020

android kotlin - ConstraintLayout set constraint programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.os.Bundle
import android.util.TypedValue
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)

            // put the text view bottom of button widget with margin
            constraintSet.connect(
                textView.id, // text view to change constraint
                TOP, // put text view top side bottom of button
                button.id, // button to put text view bellow it
                BOTTOM, // button bottom to put text view bellow it
                24.toDp(context) // margin (optional)
            )

            // horizontally center align the text view
            // text view constraint start to start of parent
            constraintSet.connect(
                textView.id,
                START,
                PARENT_ID,
                START
            )

            // text view constraint end to end of parent
            constraintSet.connect(
                textView.id,
                END,
                PARENT_ID,
                END
            )

            // finally, apply the constraint set to layout
            constraintSet.applyTo(rootLayout)
        }
    }
}

// Extension method to convert dp to equivalent pixels
fun Int.toDp(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    this.toFloat(),
    context.resources.displayMetrics
).toInt()
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="16dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set TextView Constraint"
        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:background="#FEFEFA"
        android:padding="12dp"
        android:fontFamily="sans-serif"
        android:textStyle="italic"
        android:text="Lorem ipsum dolor sit amet, consectetur
         adipiscing elit. In dapibus urna id mauris maximus,
         at placerat nibh pretium. Donec ac mi orci.
         Suspendisse potenti. Nulla id ultrices enim.
         Phasellus leo velit, porttitor sit amet rhoncus
         eu, molestie non risus."
        android:textColor="#2E5894"
        android:textSize="24sp" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android examples