今天來用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