Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

android - Trouble with ViewModel, LiveData

I have main Fragment and DialogFragment. In Start i go in dialogFragment with list of city and get one for save in LiveData

listOfCities.setOnItemClickListener { parent, view, position, id ->
            homeViewModel.selectCityTo((listOfCities.getItemAtPosition(position) as HashMap<String, String>).getValue("name"))
            Log.e("Search", homeViewModel.cityTo.value)
}

I checked through Logcat and its work. But when i returned to main Fragment, Livedata is empty. TextView(cityTo) does not change

 homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        val cityFrom = root.findViewById<TextView>(R.id.cityFrom)
        val cityTo = root.findViewById<TextView>(R.id.cityTo)
        homeViewModel.cityFrom.observe(viewLifecycleOwner, Observer {
            cityFrom.text = it
        })
        homeViewModel.cityTo.observe(viewLifecycleOwner, Observer {
            cityTo.text = it
        })

ViewModel

class HomeViewModel : ViewModel() {

    private val _cityFrom = MutableLiveData<String>()
    private val _cityTo = MutableLiveData<String>()

    val cityFrom: LiveData<String> = _cityFrom
    val cityTo: LiveData<String> = _cityTo

    fun selectCityTo(to: String){
        _cityTo.value = to
        Log.e("hViewModel", "${cityTo.value}")

    }
    fun selectCityFrom(from: String){
        _cityFrom.value = from
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should pass the activity to the ViewModelProvider (in both fragments where you create the viewmodel):

ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)

If you pass the Fragment, you will get a different ViewModel in each Fragment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...