How to update a TextView in Fragment from a second Activity using LiveData?

不打扰是莪最后的温柔 提交于 2020-01-25 06:41:29

问题


I have a fragment that starts a second activity upon some button click. This second activity is where the user makes some selections. I want to update a TextView in the fragment based on the user's selections from the second activity. I am using a ViewModelFactory in order to get access to the same ViewModel in the Fragment from within the second Activity (from the solution from Amir Raza found at: Android LiveData - how to reuse the same ViewModel on different activities?)

But the TextView is not being updated.

I found answers here:

Update textView in Fragment from Activity

But this answer does not use LiveData.

Fragment:

class CreatePlanFragment : Fragment()
    {
        private lateinit var vmCreatePlan: NameViewModel
        ...
        vmCreatePlan = ViewModelProviders.of(this, ViewModelFactory.getInstance()).get(NameViewModel::class.java)
        val tvStartReference: TextView = view.findViewById(R.id.create_plan_start_ref)
        vmCreatePlan.referenceStart.observe(this, Observer {
            tvStartReference.text = it
        })
    }   

Second Activity:

class ActivitySelectReference : AppCompatActivity()
{
    private lateinit var vmCreatePlan: NameViewModel
    ...
    vmCreatePlan = ViewModelProviders.of(this, ViewModelFactory.getInstance()).get(NameViewModel::class.java)

    reference_button_ok.setOnClickListener {
            vmCreatePlan.referenceStart.postValue("New Label")
            //vmCreatePlan.referenceStart.value ="New Label"
            finish()
        }

}

ViewModel:

class NameViewModel : ViewModel()
{
    val referenceStart: MutableLiveData<String> = MutableLiveData<String>().apply {
        value = "Old Label"
    }

    companion object
    {
        private var instance: NameViewModel? = null
        fun getInstance() = instance ?: synchronized(NameViewModel::class.java) {
            instance ?: NameViewModel().also { instance = it }
        }
    }
}

ViewModelFactory:

class ViewModelFactory : ViewModelProvider.NewInstanceFactory()
{
    override fun <T : ViewModel?> create(modelClass: Class<T>) = with(modelClass) {
        when
        {
            isAssignableFrom(NameViewModel::class.java) -> NameViewModel.getInstance()
            else -> throw IllegalArgumentException("Unknown viewModel class $modelClass")
        }
    } as T

    companion object
    {
        private var instance: ViewModelFactory? = null
        fun getInstance() = instance ?: synchronized(ViewModelFactory::class.java) {
            instance ?: ViewModelFactory().also { instance = it }
        }
    }
}

来源:https://stackoverflow.com/questions/59887014/how-to-update-a-textview-in-fragment-from-a-second-activity-using-livedata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!