android kotlin - Create TextView programmatically

Introduction

This code demonstrates how to programmatically create a TextView in an Android application using Kotlin. Programmatically creating views offers flexibility in dynamically adding UI elements during runtime based on certain conditions or user interactions.

MainActivity.kt

The MainActivity class extends AppCompatActivity and overrides the onCreate() method, which is the entry point of the activity. Here's a breakdown of the steps involved:

  • Inside onCreate(), we first set the content view of the activity using setContentView(R.layout.activity_main). This inflates the activity_main.xml layout and associates it with the activity.

  • A context variable is then created to reference the current activity context. We also define a string variable to hold the text content that will be displayed in the TextView.

  • The createTextView() extension function is called to programmatically create a TextView. This function is defined outside the MainActivity class and can be reused anywhere within the project where a TextView needs to be created dynamically.

createTextView() function

This extension function takes the Context as input and returns a TextView object after applying various customizations. Let's explore the customizations applied within this function:

  • The text property of the TextView is set using the string variable we defined earlier.

  • The text appearance is set using TextViewCompat.setTextAppearance() by referencing a predefined style (android.R.style.TextAppearance_DeviceDefault_Large) or by setting styles individually.

  • The typeface, background color, text color, text style (italic), and text size (30sp) are set using the corresponding properties of the TextView.

  • Padding is applied to the TextView using the dpToPixels() extension function to convert dp values to pixels based on the device's display metrics.

  • Layout params are set for the TextView using a LayoutParams object. Here, we set the width to MATCH_PARENT and the height to WRAP_CONTENT.

  • Finally, a unique view ID is generated for the TextView, and it's added to the ConstraintLayout using the addViewCenter() extension function, which centers the view within the parent ConstraintLayout.

addViewCenter() function

This extension function takes a ConstraintLayout and a View as input and performs the following actions:

  • It adds the view to the ConstraintLayout using addView().

  • It creates a new ConstraintSet object and clones the current constraints of the ConstraintLayout.

  • It defines margins of 16dp around the view.

  • It usesConstraintSet.connect() to connect all four sides (START, TOP, END, BOTTOM) of the view to the corresponding sides of the parent ConstraintLayout, essentially centering the view within the parent.

  • Finally, it applies theConstraintSet to the ConstraintLayout using set.applyTo(this).

dpToPixels() function

This extension function is used to convert dp (density-independent pixels) values to pixels based on the device's display metrics. This ensures consistent sizing across different devices with varying screen densities.

activity_main.xml

This XML file defines the layout of the activity. In this case, it contains a ConstraintLayout as the root element, which serves as the container for the programmatically created TextView.

Summary

By combining these components, this code snippet demonstrates a practical approach to dynamically creating and customizing TextViews in an Android application using Kotlin. This approach offers greater flexibility in building user interfaces that can adapt to different scenarios or user interactions.

Table Summary

PropertyFunctionality
ContextReference to the current activity context
String variableHolds the text content to be displayed in the TextView
createTextView()Extension function to programmatically create a TextView
Text propertySets the text content of the TextView
TextViewCompat.setTextAppearance()Sets the text appearance of the TextView
TypefaceSets the font of the TextView
Background colorSets the background color of the TextView
Text colorSets the text color of the TextView
Text styleSets the text style of the TextView (e.g., italic)
Text sizeSets the text size of the TextView
dpToPixels()Converts dp values to pixels
LayoutParamsSets the layout parameters of the TextView (width and height)
View IDA unique identifier for the TextView
addViewCenter()Extension function to add a view to the ConstraintLayout and center it
ConstraintSetA class for defining and applying constraints between views in a ConstraintLayout
ConstraintLayoutA ViewGroup subclass for building complex layouts with a flexible system for positioning its children


MainActivity.kt

package com.example.jetpack

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.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams.PARENT_ID
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.widget.TextViewCompat
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val context = this

        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry."

        createTextView().apply {
            text = string
            constraintLayout.addViewCenter(context,this)
        }
    }
}


// extension function to create a text view programmatically
fun Context.createTextView():TextView{
    return TextView(this).apply {
        text = "Sample TextView" // text

        // set text view text appearance
        TextViewCompat.setTextAppearance(
            this,
            android.R.style.TextAppearance_DeviceDefault_Large
        )

        // set text appearance or individually set styles
        typeface = Typeface.MONOSPACE // font

        background = ColorDrawable(Color.parseColor("#FFFAF0")) // background color
        setTextColor(Color.parseColor("#A2006D")) // text color

        setTypeface(typeface, Typeface.ITALIC) // text style
        setTextSize(TypedValue.COMPLEX_UNIT_SP,30F) // text size

        val padding = 25.dpToPixels(this@createTextView)
        setPadding(padding,padding,padding,padding) // padding

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

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


// extension function to add view to constraint layout center
fun ConstraintLayout.addViewCenter(context:Context, view:View){
    addView(view)

    // initialize a new constraint set
    val set = ConstraintSet()
    set.clone(this)

    val margin = 16.dpToPixels(context)

    // put view center in parent
    set.connect(view.id,ConstraintSet.START,PARENT_ID,
        ConstraintSet.START,margin)

    set.connect(view.id,ConstraintSet.TOP,PARENT_ID,ConstraintSet.TOP)

    set.connect(view.id,ConstraintSet.END,PARENT_ID,
        ConstraintSet.END,margin)

    set.connect(view.id,ConstraintSet.BOTTOM,PARENT_ID,ConstraintSet.BOTTOM)

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


// extension function to convert dp to pixels
fun Int.dpToPixels(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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity"/>
More android kotlin tutorials