Search code examples
androidandroid-studiokotlinandroid-layouttextview

How to declare textview inside a function in Kotlin?


So I have this function below and I want to declare a textview inside it, however using findViewById seems not working. What should I do so I can declare a textview inside a function?

fun addingNewText(idt: Int): TextView {
            //val newtext = findViewById(R.id.idt) as TextView        
            val parameter = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)    
            //newtext.setLayoutParams(parameter)      
            //newtext.tag = idt.toString()
            //return newtext
}

Solution

  • I'm assuming you mean you want to create a new TextView. Like most classes, you can just call its constructor. for example:

    val newtext = TextView(this)
    

    (this here is a context, for example an Activity)