Darshan Miskin
Darshan Miskin

Reputation: 844

Dynamically create controls in android using Kotlin

Using java, to create a control dynamically we use something like TextView textview=new TextView(getApplicationContext());

how can the same be done in Kotlin? var textview = TextView does't work, nor does var textview as TextView

unfortunately, haven't even encountered any good kotlin tutorials for android.

update-Actually am trying to create dynamic listview with a custom layout.

Upvotes: 1

Views: 1522

Answers (3)

Seanghay
Seanghay

Reputation: 1086

You can also use var myTextView: TextView? = TextView(this) To assign text to TextView myTextView?.setText("Hello")

But myTextView variable cannot be null.

Upvotes: 0

Avijit Karmakar
Avijit Karmakar

Reputation: 9408

To create a textview dynamically, you have to call the constructor of textview and store it in a variable like this:

var myTextview = TextView(this);

You have to write this code in an activity or a fragment because this will represent an activity or a fragment.

Then use textview's all the methods like: setText();

myTextview.setText("Hello");

Upvotes: 0

zsmb13
zsmb13

Reputation: 89608

You can, by calling the constructor of TextView, like so:

var textview = TextView(this) // "this" being the Activity

See creating instances in the official documentation.

Upvotes: 5

Related Questions