viewmodel基本用法
创建viewmodel
class myviewmodel: viewmodel() {
}实现一个计数器
class myviewmodel : viewmodel() {
var count = 0
}在activity使用viewmodel,获取viewmodel的实例需要通过viewmodelprovider。点击按钮一次计数器加1
override fun oncreate(savedinstancestate: bundle?) {
super.oncreate(savedinstancestate)
enableedgetoedge()
binding = activityclickbinding.inflate(layoutinflater)
setcontentview(binding.root)
viewmodel = viewmodelprovider(this).get(myviewmodel::class.java)
binding.clickbutc.setonclicklistener {
viewmodel.count++
refreshcount()
}
refreshcount()
}
private fun refreshcount() {
binding.clicktvtext.text = viewmodel.count.tostring()
}
旋转屏幕后,计数器的数据仍然存在

向viewmodel传递参数
改进上面的例子,保证退出程序后,重新打开,数据任然存在。
修改viewmodel
class myviewmodel(counter: int) : viewmodel() {
var count = counter
}counter记录之前保存的值
创建viewmodelprovider.factory ,向myviewmodel的构造函数传递数据。添加构造函数,重写create方法,
class myviewmodelfactory(private val counter: int) : viewmodelprovider.factory {
override fun <t : viewmodel> create(modelclass: class<t>): t {
return myviewmodel(counter) as t
}
}修改activity
class clickactivity : componentactivity() {
lateinit var viewmodel: myviewmodel
lateinit var binding:activityclickbinding
lateinit var sp: sharedpreferences
override fun oncreate(savedinstancestate: bundle?) {
super.oncreate(savedinstancestate)
enableedgetoedge()
binding = activityclickbinding.inflate(layoutinflater)
setcontentview(binding.root)
sp = getsharedpreferences("data",mode_private)
val countsp = sp.getint("count",0)
viewmodel = viewmodelprovider(this, myviewmodelfactory(countsp)).get(myviewmodel::class.java)
binding.clickbutc.setonclicklistener {
viewmodel.count++
refreshcount()
}
refreshcount()
}
private fun refreshcount() {
binding.clicktvtext.text = viewmodel.count.tostring()
}
override fun onpause() {
super.onpause()
sp.edit{
putint("count",viewmodel.count)
}
}
}到此这篇关于android开发(kotlin) viewmodel基本用法的文章就介绍到这了,更多相关android viewmodel用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论