Dynamically create controls in android using Kotli

2019-06-06 01:31发布

问题:

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.

回答1:

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.



回答2:

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");


回答3:

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

But myTextView variable cannot be null.