在Kotlin 1.3.2 Activity中使用ViewModelProvider

  • Post author:
  • Post category:其他


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 版权协议,转载请附上原文出处链接和本声明。