Home > Software engineering >  How to declare textview inside a function in Kotlin?
How to declare textview inside a function in Kotlin?

Time:09-07

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
}

CodePudding user response:

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)

CodePudding user response:

If you're trying create a new view you should use Ivo's answer, Or if you're trying get view in a layout, you should use val newtext = findViewById<TextView>(R.id.idt). Because in kotlin you have to infer what type of view you are trying retrieve. Refer to this thread for more clearance.

  • Related