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