请注意,如果使用 findViewById < > () from activity,那么如果从片段调用它,它将无法工作。您需要将视图分配给变量。这是我的箱子
这不管用
class MainActivity{
fun onCreate(...){
//works
setMyText("Set from mainActivity")
}
fun setMyText(s: String){
findViewById<TextView>(R.id.myText).text = s
}
}
________________________________________________________________
class ProfileFragment{
...
fun fetchData(){
// doesn't work
(activity as MainActivity).setMyText("Set from profileFragment")
}
}
这个管用
class MainActivity{
private lateinit var myText: TextView
fun onCreate(...){
myText = findViewById(R.id.myText)
// works
setMyText("Set from mainActivity")
}
fun setMyText(s: String){
myText.text = s
}
}
________________________________________________________________
class ProfileFragment{
...
fun fetchData(){
// works
(activity as MainActivity).setMyText("Set from profileFragment")
}
}