Created
May 15, 2020 05:33
-
-
Save AgiMaulana/a55a8478fe6cfbabcb69bb8cf94f5cb6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.KeyEvent | |
import android.view.View | |
import android.widget.EditText | |
import com.google.android.material.textfield.TextInputEditText | |
import com.justika.client.extention.addOnTextChangedListener | |
class CodeVerificationUiUtil(private val editTexts: List<EditText>) { | |
private lateinit var currentEditText: EditText | |
/** | |
* Listen edit texts on changed | |
*/ | |
var codeVerificationUiListener: CodeVerificationUiListener? = null | |
/** | |
* Start bind given editTexts | |
* Should be called on onCreate | |
*/ | |
fun bind(){ | |
editTexts.forEach { | |
it.setOnFocusChangeListener(this::onOtpFieldFocusChanged) | |
it.addOnTextChangedListener(onTextChanged = this::onMfaCodeFieldTextChanged) | |
it.setOnKeyListener(this::onOtpBackSpaced) | |
} | |
} | |
private fun onOtpFieldFocusChanged(view: View, hasFocus: Boolean) { | |
if (!hasFocus) return | |
editTexts | |
.firstOrNull { | |
it.text?.isEmpty() == true | |
}?.requestFocus() ?: editTexts.last().requestFocus() | |
currentEditText = view as TextInputEditText | |
} | |
private fun onMfaCodeFieldTextChanged(text: String) { | |
onOtpFieldFocusChanged(currentEditText, true) | |
formFillCheck() | |
} | |
private fun onOtpBackSpaced(v: View?, keyCode: Int, event: KeyEvent?): Boolean { | |
//You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_ | |
if (keyCode == KeyEvent.KEYCODE_DEL && event?.action == KeyEvent.ACTION_DOWN) { | |
//this is for backspace | |
editTexts | |
.lastOrNull { | |
it.text?.isEmpty() == false | |
}?.let { | |
it.setText("") | |
it.requestFocus() | |
} | |
return true | |
} | |
return false | |
} | |
fun getCode() = | |
editTexts.joinToString(separator = "") { it.text.toString() } | |
private fun formFillCheck() { | |
val isAllFieldsFilled = editTexts.none { | |
it.text?.isEmpty() == true | |
} | |
codeVerificationUiListener?.onCodeChanged(getCode(), isAllFieldsFilled) | |
} | |
interface CodeVerificationUiListener { | |
/** | |
* @param code Typed code | |
* @param isFilled indicate is all edit texts filled or not, | |
* true if filled, false otherwise | |
*/ | |
fun onCodeChanged(code: String, isFilled: Boolean) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment