问题
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