Kotlin Create View Programmatically
The following android application development tutorial will demonstrate how we can create a View programmatically using Kotlin programming language. This tutorial also demonstrates how we can add the newly created View to ViewGroup.
In this tutorial, we created a TextView widget programmatically inside the main activity kotlin file and we put this TextView widget to a ConstraintLayout ViewGroup. The root ConstraintLayout is placed inside the XML layout file but there is no TextView widget. This ViewGroup has only a Button widget inside it. We will create a TextView widget on the Button click event and put it at the bottom of the Button widget inside ConstraintLayout.
So, the ConstraintLayout and Button widgets are already placed in XML layout using tags. We have to create a TextView widget programmatically and also have to place it below the Button widget inside the ConstarintLayout ViewGroup.
TextView is a native android SDK widget. TextView is a user interface element that displays text to the user. The TextView() constructor allows us to initialize a new instance of the TextView widget. This constructor has a required argument name ‘context’, so we have to pass a Context object to create a new TextView widget programmatically.
We have to create a layout parameters object for the TextView to define the position and size of this TextView inside the ViewGroup. Here we created a ‘ConstraintLayout.LayoutParams’ instance to define TextView layout parameters. It also defines the margin and position of TextView.
The TextView class’s various methods allow us to set the TextView properties programmatically. Such as we can set the TextView text, text size, text color, typeface, TextView background color, TextView padding, an id, and a click listener.
Finally, the ConstraintLayout’s addView() method allows us to add the newly created TextView widget to the ConstraintLauout ViewGroup with all of its defined attributes.
This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to test how we create a View programmatically in an android application.
And how we add this View to the ViewGroup programmatically with the specified size and position and attributes. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
In this tutorial, we created a TextView widget programmatically inside the main activity kotlin file and we put this TextView widget to a ConstraintLayout ViewGroup. The root ConstraintLayout is placed inside the XML layout file but there is no TextView widget. This ViewGroup has only a Button widget inside it. We will create a TextView widget on the Button click event and put it at the bottom of the Button widget inside ConstraintLayout.
So, the ConstraintLayout and Button widgets are already placed in XML layout using tags. We have to create a TextView widget programmatically and also have to place it below the Button widget inside the ConstarintLayout ViewGroup.
TextView is a native android SDK widget. TextView is a user interface element that displays text to the user. The TextView() constructor allows us to initialize a new instance of the TextView widget. This constructor has a required argument name ‘context’, so we have to pass a Context object to create a new TextView widget programmatically.
We have to create a layout parameters object for the TextView to define the position and size of this TextView inside the ViewGroup. Here we created a ‘ConstraintLayout.LayoutParams’ instance to define TextView layout parameters. It also defines the margin and position of TextView.
The TextView class’s various methods allow us to set the TextView properties programmatically. Such as we can set the TextView text, text size, text color, typeface, TextView background color, TextView padding, an id, and a click listener.
Finally, the ConstraintLayout’s addView() method allows us to add the newly created TextView widget to the ConstraintLauout ViewGroup with all of its defined attributes.
This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to test how we create a View programmatically in an android application.
And how we add this View to the ViewGroup programmatically with the specified size and position and attributes. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt
package com.cfsuman.kotlintutorials
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.util.TypedValue
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get the context
val context = this;
// Get the widgets reference from XML layout
val rootLayout = findViewById<ConstraintLayout>(R.id.root_layout);
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
// Disable the button itself
it.isEnabled = false;
// Create a new TextView instance programmatically
val textView = TextView(context)
// Creating a ConstraintLayout.LayoutParams object for text view
val params = LayoutParams(
LayoutParams.MATCH_PARENT, // This will define text view width
LayoutParams.WRAP_CONTENT // This will define text view height
)
// set the new widget specific position inside layout
params.topToBottom = button.id
// Add margin to the text view
params.setMargins(10,16,10,10)
textView.apply {
// Now, specify the text view width and height (dimension)
layoutParams = params
// Display some text on the newly created text view
text = "Lorem ipsum dolor sit amet, consectetur" +
" adipiscing elit. Etiam felis lacus, eleifend" +
"sed magna id, molestie cursus nibh. Phasellus" +
"posuere mi tellus, eu sollicitudin leo vehicula" +
"vitae. Quisque bibendum fringilla orci. Ut" +
"imperdiet dolor sit amet libero fringilla," +
"sit amet rutrum erat condimentum."
// Set the text view font/text size
setTextSize(TypedValue.COMPLEX_UNIT_SP,22F)
// Set the text view text color
setTextColor(Color.parseColor("#333399"))
// Make the text viw text bold italic
setTypeface(textView.typeface, Typeface.ITALIC)
// Change the text view font
typeface = Typeface.MONOSPACE
// Change the text view background color
setBackgroundColor(Color.parseColor("#FEFEFA"))
// Put some padding on text view text
setPadding(100,100,100,100)
// Set a click listener for newly generated text view
textView.setOnClickListener{
Toast.makeText(
context,"TextView clicked.", Toast.LENGTH_SHORT
).show()
}
// Set an id for the text view
textView.id = Random.nextInt()
// Finally, add the text view to the view group
rootLayout.addView(textView)
}
}
}
}
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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp"
android:background="#DCDCDD">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create TextView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>


- kotlin - Labeled loop break example
- kotlin - withIndex library function example
- kotlin - While loop example
- kotlin - If else example
- kotlin - Function example
- kotlin - Function parameter default value example
- kotlin - List and ArrayList example
- kotlin - RecyclerView example
- kotlin - RadioGroup and RadioButton example
- kotlin - AlertDialog example