Creating a TextView programmatically in Android can be done by instantiating a new TextView object and configuring its properties.
First, you need to import the TextView class from the Android SDK. You can do this by adding the following line at the top of your activity or fragment class:
import android.widget.TextView
Next, you can create a new instance of the TextView class. For example:
val myTextView = TextView(this)
In this example, this
is passed as the context parameter to the TextView constructor, which sets the context for the TextView.
Once you have created the TextView, you can configure its properties such as text, text size, text color, and layout parameters. For example:
myTextView.text = "Hello, World!"
myTextView.textSize = 20f
myTextView.setTextColor(Color.BLACK)
val layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT)
myTextView.layoutParams = layoutParams
In this example, the text, text size, and text color properties of the TextView are set. The layout parameters are also set, which determine the position and size of the TextView within the layout.
Finally, you need to add the TextView to your layout. For example, if you are using a ConstraintLayout, you can add the TextView to the layout like this:
val constraintLayout = findViewById<ConstraintLayout>(R.id.constraint_layout)
constraintLayout.addView(myTextView)
In this example, the TextView is added to the ConstraintLayout with the ID "constraint_layout".
It's important to note that when creating a TextView programmatically, you need to set its layout parameters explicitly, otherwise it won't be displayed on screen.
In summary, creating a TextView programmatically in Android involves importing the TextView class, instantiating a new TextView object, configuring its properties, and adding it to a layout.