Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Dynamic TextView in Kotlin

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Android TextView is an user interface that is used to display some text to the user.

In this article we will be discussing how to programmatically create a TextView in Kotlin .

Let’s start by first creating a project in Android Studio. To do so, follow these instructions:

  • Click on File, then New and then New Project and give name whatever you like
  • Then, select Kotlin language Support and click next button.
  • Select minimum SDK, whatever you need.
  • Select Empty activity and then click finish.

Modify activity_main.xml file

Second step is to design our layout page. Here, we will use the RelativeLayout to get the TextView from the Kotlin file.

<?xml version="1.0" encoding="utf-8"?>

Create TextView in MainActivity.kt file

Open app/src/main/java/yourPackageName/MainActivity.kt. In this file, we declare a variable TextView to create the TextView widget like this:

     val textView = TextView(this)
     //setting height and width
    textView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)

then add the widget in layout using this:

        // Add TextView to LinearLayout

package com.geeksforgeeks.myfirstKotlinapp
import android.os.Bundle
import android.util.TypedValue
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?)
        val layout = findViewById<RelativeLayout>(
        // Create TextView programmatically.
        val textView = TextView(this)
        // setting height and width
        textView.layoutParams= RelativeLayout.LayoutParams(
        // setting text
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40f)
        // onClick the text a message will be displayed "HELLO GEEK"
            Toast.makeText(this@MainActivity, "HELLO GEEK"
        // Add TextView to LinearLayout
        layout ?.addView(textView)

AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>

Run as Emulator:

My Personal Notes arrow_drop_up
Last Updated : 18 Feb, 2021
Like Article
Save Article
Similar Reads
Related Tutorials