diff --git a/app/src/main/java/org/thoughtcrime/securesms/components/registration/VerificationCodeView.kt b/app/src/main/java/org/thoughtcrime/securesms/components/registration/VerificationCodeView.kt index 789742cb59..395d2b1a12 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/components/registration/VerificationCodeView.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/components/registration/VerificationCodeView.kt @@ -1,6 +1,8 @@ package org.thoughtcrime.securesms.components.registration import android.content.Context +import android.text.Editable +import android.text.TextWatcher import android.util.AttributeSet import android.widget.FrameLayout import com.google.android.material.textfield.TextInputLayout @@ -9,6 +11,7 @@ import org.thoughtcrime.securesms.R class VerificationCodeView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) { private val containers: MutableList = ArrayList(6) + private val textWatcher = PasteTextWatcher() private var listener: OnCodeEnteredListener? = null private var index = 0 @@ -22,6 +25,7 @@ class VerificationCodeView @JvmOverloads constructor(context: Context, attrs: At containers.add(findViewById(R.id.container_five)) containers.forEach { it.editText?.showSoftInputOnFocus = false } + containers.forEach { it.editText?.addTextChangedListener(textWatcher) } } fun setOnCompleteListener(listener: OnCodeEnteredListener?) { @@ -41,8 +45,9 @@ class VerificationCodeView @JvmOverloads constructor(context: Context, attrs: At } fun delete() { - if (index <= 0) return - containers[--index].editText?.setText("") + if (index < 0) return + val editText = if (index == 0) containers[index].editText else containers[--index].editText + editText?.setText("") containers[index].editText?.requestFocus() } @@ -57,4 +62,29 @@ class VerificationCodeView @JvmOverloads constructor(context: Context, attrs: At interface OnCodeEnteredListener { fun onCodeComplete(code: String) } + + inner class PasteTextWatcher : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} + + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} + + override fun afterTextChanged(s: Editable?) { + if (s == null) { + return + } + + if (s.length > 1) { + val enteredText = s.toList() + enteredText.forEach { + val castInt = it.digitToIntOrNull() + if (castInt == null) { + s.clear() + return@forEach + } else { + append(castInt) + } + } + } + } + } }