我希望第一个片段通过来自第二个片段的LiveData来观察信息。我尝试执行相同的操作,但仅在1 Fragment中起作用,但是它起作用了,但是一旦我想在其他Fragment中接收数据,它就会停止起作用(textView没有文本)。我该如何解决这个问题?
SharedViewModel:
class SharedViewModel : ViewModel() {
private val selected : MutableLiveData<Person> = MutableLiveData<Person>()
fun select(person: Person){
selected.value = person
}
fun getSelected(): LiveData<Person>{
return selected
}
}
第一个片段:
class FirstFragment : Fragment() {
private lateinit var sharedViewModel: SharedViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
sharedViewModel =
ViewModelProviders.of(this).get(SharedViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
val textView: TextView = root.findViewById(R.id.text_home)
sharedViewModel.getSelected().observe(viewLifecycleOwner, Observer{
textView.text = it.name
})
return root
}
}
第二个片段:
class SecondFragment : Fragment() {
private lateinit var sharedViewModel: SharedViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
sharedViewModel =
ViewModelProviders.of(this).get(SharedViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_dashboard, container, false)
val textView: TextView = root.findViewById(R.id.text_dashboard)
val person = Person("John")
val newPerson = Person("Anton")
val button2: Button = root.findViewById(R.id.button2)
val button: Button = root.findViewById(R.id.button)
button2.setOnClickListener {
sharedViewModel.select(person)
}
button.setOnClickListener {
sharedViewModel.select(newPerson)
}
return root
}
}
班级人员:
class Person (var name: String) {
}