VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/dynamic-textview-in-kotlin/

⇱ Dynamic TextView in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dynamic TextView in Kotlin

Last Updated : 24 Feb, 2025

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 .

Step by Step Implementation

Step 1: Create a new project

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.

Step 2: 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.

activity_main.xml:


Step 3: Create TextView in MainActivity.kt file

Navigate to app > src > main > java/kotlin > {package-name} > MainActivity.kt. In this file, we declare a variable TextView to create the TextView widget like this:

val textView = TextView(this)

textView.layoutParams= LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)

then add the widget in layout using this:

layout.addView(textView)

MainActivity File:

Output:

Comment
Article Tags:

Explore