Android学习笔记24

今天来用checkbox首先先在xml新增

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

接着是在登入的时候去判断是否有被打勾

binding.login.setOnClickListener {
    if (binding.checkbox.isChecked){
        viewModel.result.postValue(MainDialogResult.Saveandlogin(binding.account.text.toString() , binding.password.text.toString() , binding.checkbox.isChecked))
        dismiss()
    }
    else{
        viewModel.result.postValue(MainDialogResult.Login( false))
        dismiss()
    }
}

那我这边有小改一下maindialogresult的资料

data class Saveandlogin(val account: String , val password: String , val check: Boolean): MainDialogResult()
data class Login(val check:Boolean):MainDialogResult()
object Cancel: MainDialogResult()

当他没有打勾的时候,只回传boolean值以确保下次打开也是没有打勾的
相对的打勾也会再下次打开的时候也保存打勾(预设是都不打勾)
然後在activity监听回传是哪一种结果

viewModel.result.observe(this){
    when(it){
        is MainDialogResult.Saveandlogin ->{
            mainViewModel.saveddata(it.account,it.password)
            mainViewModel.savecheck(it.check)
        }
        is MainDialogResult.Login ->{
            mainViewModel.remove()
            mainViewModel.savecheck(it.check)
        }
        is MainDialogResult.Cancel ->{
            Toast.makeText(this,"cancel",Toast.LENGTH_SHORT).show()
        }
    }
}

则会对应到相应的viewmodel

fun saveddata(account: String, password: String ) {
    Repository(getApplication()).savedpreferences(account,password)
}
fun savecheck(check: Boolean){
    Repository(getApplication()).savedchecked(check)
}

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()
}
fun remove(){
    Repository(getApplication()).remove()
}
而我checkbox的boolean值是用建构值传的
class FragmentDialog(val boolean: Boolean): DialogFragment() {
//do something
}

因为我是使用dialogfragment他是不能直接使用sharedpreference的,所以还在想要如何把activitysharedpreference到的帐号密码传到dialogfragment


<<:  27. 解释 CSS 的 BFC(Block Formatting Context)

>>:  Day18 Android - RecyclerView应用

GNU Debugger

GNU Debugger,简称 GDB,是 GNU 软件系统中的除错器,由於其具有可移植的优点,在现...

[Java Day15] 4.3. 参数

教材网址 https://coding104.blogspot.com/2021/06/java.h...

[Day 5] Course 1_Foundation - 资料分析工具及职涯探索

《30天带你上完 Google Data Analytics Certificate 课程》系列将...

Day 10:Python基本介绍03 | List、Tuple

各位早安阿~ 不知不觉间已经来到铁人赛第十天,也就是过完1/3了呢,想想还真是快。只不过今天就开学了...

[Day29] 後端13:後端Code总结

不过有些需要下的指令可不能省喔~ .env APP_NAME=Laravel APP_ENV=loc...