class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewModelProvider = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application))
val viewModel = viewModelProvider.get(MyViewModel::class.java)
viewModel.number.observe(this, Observer { textView.text = it.toString() })
buttonPlus.setOnClickListener{
viewModel.modifyNumber(1)
}
buttonmunite.setOnClickListener {
viewModel.modifyNumber(-1)
}
}
}
使用ViewModelProvider获取viewModelProvider类,通过viewModelProvider获取viewModel
版权声明:本文为tjjingpan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。