在Kotlin 1.3.2 Activity中使用ViewModelProvider

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

你可能感兴趣的:(kotlin,android,开发语言)