Updating value inside fragment from activity

☆樱花仙子☆ 提交于 2020-12-15 16:38:42

问题


I wish to transfere my old app to MVVM, so can you please help me with this test:

Shared ViewModel:

class SharedViewModel : ViewModel() {

    private var _numberF1 = MutableLiveData<Int>().apply { postValue(0)}
    val numberF1: LiveData<Int>
        get() = _numberF1


    fun addNumberF1() {
         _numberF1.value = _numberF1.value?.plus(1)
    }
}

Fragment:

class Fragment1 : Fragment() {

    companion object {
        fun newInstance() = Fragment1()
    }

    private lateinit var viewModel: SharedViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view: View = inflater.inflate(R.layout.fragment_1, container, false)
        
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(SharedViewModel::class.java)

        viewModel.numberF1.observe(this, {
        Log.d("DTAG","Should be updated")
        textViewNumberF1.text = it.toString()
    })

    }

}

MainActivity:

    class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewModel = ViewModelProvider(this).get(SharedViewModel::class.java)

        var fragment1 = Fragment1.newInstance()
        navigateToFragment(fragment1)

        buttonFrag1Up.setOnClickListener { viewModel.addNumberF1() }

    }

    private fun navigateToFragment(fragment: Fragment) {

        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.addToBackStack(null)
        fragmentTransaction.replace(R.id.mainFrame, fragment)
        fragmentTransaction.commit()

    }
}

The value is no being updated What is the right approach to this?


回答1:


If you want to get shared viewModel you should write in your fragment this :

val viewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)

instead of what you have :

val viewModel = ViewModelProvider(this).get(SharedViewModel::class.java)


来源:https://stackoverflow.com/questions/64832068/updating-value-inside-fragment-from-activity

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