片段无法通过sharedViewModel和LiveData进行通信

问题描述 投票:0回答:1

我希望第一个片段通过来自第二个片段的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) {
}
android android-fragments kotlin android-livedata
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.