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"
}
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:
Do not instantiate views inside onCreateView() try using onViewCreated() to instantiate.
use kotlin extensions or databinding to access views it saves a whole lot of trouble and actually easier to use.