今天用了sharedpreferences,在mvvm架构上要使用respository来当作model来传递资料
那sharedpreference如果不是写在activity记得要把context传进建构值
class Repository (context: Context){
private val sharedPreferences = context.getSharedPreferences("User", Context.MODE_PRIVATE)
private val editor = sharedPreferences.edit()
fun savedpreferences(account:String , password:String){
editor.putString("account",account).putString("password",password).commit()
}
fun getpreferences(): SharedPreferences? {
return sharedPreferences
}
fun clearpreference(){
editor.clear().commit()
}
}
然後是viewmodel
class MainViewModel(application: Application): AndroidViewModel(application) {
fun saveddata(account: String, password: String) {
Repository(getApplication()).savedpreferences(account,password)
}
fun getdata(){
val account = Repository(getApplication()).getpreferences()!!.getString("account","")
val password = Repository(getApplication()).getpreferences()!!.getString("password","")
Toast.makeText(getApplication(),account+password,Toast.LENGTH_SHORT).show()
}
fun cleardata(){
Repository(getApplication()).clearpreference()
}
}
还有一个在activity监听的按钮
viewModel.result.observe(this){
when(it){
is MainDialogResult.Ok ->{
mainViewModel.saveddata(it.account,it.password)
}
is MainDialogResult.Cancel ->{
Toast.makeText(this,"cancel",Toast.LENGTH_SHORT).show()
}
}
}
成果如下
clear之後
<<: [Android Studio 30天自我挑战] SeekBar元件介绍
大家好! 光是复杂的 JSON 资料就要看到眼花了,如果又全部缩成一行,我不敢说了。 我们进入今天的...
我理想的情况是, 事前planing好API(req、res),完成每只api估时,妥善把开发过程分...
网路层(2) 3.zigbee ZigBee是一个短距离的通讯由ZigBee联盟所制定的一个无线传...
以实务来说,总是会有一些情况导致使用者没办法正常收到认证码,所以系统必须具备 retry on fa...
前言:桶排序又名箱排序,究竟这个特殊的排序法是怎麽运作的,让我们一来探讨! 桶排序: 和上一篇的基数...