Search code examples
androidkotlinandroid-context

How to update textview declared in OnViewCreated from another function


I am trying to update the TextView of my fragment in Kotlin. How would I be able to update it while having the TextView declared in the onViewCreated of my fragment?

Inside onViewCreated function:

val txt = view.findViewById<View>(R.id.txt) as TextView

In another function:

fun update(){
    txt.text= "Hello"
}

Solution

  • You can't access it if its declared inside the onCreateView()

    instead, try this in class level.

    class MyFragment : Fragment(){
    
       lateinit var txt: TextView
    
    }
    

    then assign your textView to the variable.

    Although I have 2 suggestions for you:

    1. Do not instantiate views inside onCreateView() try using onViewCreated() to instantiate.

    2. use kotlin extensions or databinding to access views it saves a whole lot of trouble and actually easier to use.