1

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

that's helpful, trying to create an adapter for listview like var listadapter=ListAdapter(this) doesn't work though.
The Kotlin syntax is good, that would call the constructor. However, ListAdapter is an interface so it has no constructor and cannot be instantiated. You can only create a concrete subclass that implements ListAdapter. Tip: Make an adapter class that extends BaseAdapter (which implements ListAdapter). Though, this has nothing to do with Kotlin, it is just the regular (java) Android sdk.
I am very well versed with android java.. its kotlin syntax that i am experimenting with. Btw thanks for the official document​ation link. :)
0

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

Comments

0

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

But myTextView variable cannot be null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.