Here is an easy way to make a reactive Android pin code feature with secure data.
package com.him.secured_pincode.ui.main
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class PinCodeViewModel : ViewModel() {
val pinCode = MutableLiveData<String>().also {
it.value = ""
}
val numPadListener = object : NumPadListener {
override fun onNumberClicked(number: Char) {
val existingPassCode = pinCode.value ?: ""
val newPassCode = existingPassCode + number
pinCode.postValue(newPassCode)
}
override fun onEraseClicked() {
val droppedLast = pinCode.value?.dropLast(1) ?: ""
pinCode.postValue(droppedLast)
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="pinCode"
type="androidx.lifecycle.MutableLiveData<java.lang.String>" />
</data>
....
<View
android:id="@+id/dot1"
android:layout_width="@dimen/pincode_dot_size"
android:layout_height="@dimen/pincode_dot_size"
android:background="@drawable/pass_code_dot_selector"
<-- We will change the first dot to a purple dot when the user entered the first pin code -->
android:enabled="@{pinCode.length() >= 1}" />
<View
android:id="@+id/dot2"
android:layout_width="@dimen/pincode_dot_size"
android:layout_height="@dimen/pincode_dot_size"
android:layout_marginStart="16dp"
android:background="@drawable/pass_code_dot_selector"
android:enabled="@{pinCode.length() >= 2}" />
...
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="numPadListener"
type="com.him.secured_pincode.ui.main.NumPadListener" />
</data>
...
<Button
style="@style/passCodeButton"
android:onClick="@{(v) -> numPadListener.onNumberClicked('1')}"
android:text="1" />
<Button
style="@style/passCodeButton"
android:layout_marginStart="24dp"
android:onClick="@{(v) -> numPadListener.onNumberClicked('2')}"
android:text="2" />
...
From us to your inbox weekly.