Dynamically create controls in android using Kotlin

蹲街弑〆低调 提交于 2019-12-08 06:42:37

问题


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.



来源:https://stackoverflow.com/questions/44138142/dynamically-create-controls-in-android-using-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!