package com.example.welcomeapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import android.widget.TextView
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val layout = ConstraintLayout(this).apply {
id = ConstraintLayout.generateViewId()
layoutParams = ConstraintLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
}
val welcomeText = TextView(this).apply {
id = TextView.generateViewId()
text = "Welcome to the App!"
textSize = 24f
}
layout.addView(welcomeText, ConstraintLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT))
val set = ConstraintSet()
set.clone(layout)
set.connect(welcomeText.id, ConstraintSet.TOP, layout.id, ConstraintSet.TOP)
set.connect(welcomeText.id, ConstraintSet.BOTTOM, layout.id, ConstraintSet.BOTTOM)
set.connect(welcomeText.id, ConstraintSet.START, layout.id, ConstraintSet.START)
set.connect(welcomeText.id, ConstraintSet.END, layout.id, ConstraintSet.END)
set.applyTo(layout)
setContentView(layout)
}
}We create a ConstraintLayout as the root layout programmatically. Then, we add a TextView with the text "Welcome to the App!". Using ConstraintSet, we center the TextView horizontally and vertically by connecting its edges to the parent layout's edges. Finally, we set the ConstraintLayout as the content view of the activity.