android kotlin - Add view to ConstraintLayout programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.widget.TextViewCompat


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 button = findViewById<Button>(R.id.button)

        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry. Lorem Ipsum has been the" +
                " industry's standard dummy text ever since the 1500s," +
                " when an unknown printer took a galley of type" +
                " and scrambled it to make a type specimen book."


        button.setOnClickListener {
            val textView = TextView(context)
            textView.text = string

            // Set text view text appearance
            /*TextViewCompat.setTextAppearance(
                textView,
                android.R.style.TextAppearance_DeviceDefault_Large
            )*/

            // Add other configurations for the text view
            textView.apply {
                // text view font
                typeface = Typeface.MONOSPACE

                // text view background color
                background = ColorDrawable(
                    Color.parseColor("#F0EAD6"))

                // text view text color
                setTextColor(Color.parseColor("#87421F"))

                // text view text style
                setTypeface(textView.typeface,Typeface.ITALIC)
                //setTypeface(Typeface.SANS_SERIF,Typeface.ITALIC)

                // text view text size
                setTextSize(TypedValue.COMPLEX_UNIT_SP, 24F)

                // text view text padding
                setPadding(12.toDp(context),12.toDp(context),
                    12.toDp(context),12.toDp(context))
            }

            // text view width and height
            val params = LayoutParams(
                LayoutParams.MATCH_PARENT, // width
                LayoutParams.WRAP_CONTENT // height
            )

            // layout params for text view
            textView.layoutParams = params

            // generate a view id for text view
            textView.id = View.generateViewId()

            // finally, add the text view to constraint layout
            rootLayout.addView(textView)


            // Initialize a new constraint set
            val constraintSet = ConstraintSet()
            constraintSet.clone(rootLayout)

            // put the text view bottom of button with margin
            constraintSet.connect(
                textView.id,
                ConstraintSet.TOP,
                R.id.button,
                ConstraintSet.BOTTOM,
                24.toDp(context)
            )

            // start constraint with margin
            constraintSet.connect(
                textView.id,
                ConstraintSet.START,
                R.id.rootLayout,
                ConstraintSet.START,
                16.toDp(context)
            )

            // end constraint with margin
            constraintSet.connect(
                textView.id,
                ConstraintSet.END,
                R.id.rootLayout,
                ConstraintSet.END,
                16.toDp(context)
            )

            // finally, apply the constraint set to constraint 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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:text="Create textView And Add"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>