Support pasting in verification code view.

This commit is contained in:
Nicholas 2023-03-10 13:00:34 -05:00 committed by GitHub
parent 643d96a896
commit f22daccde6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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<TextInputLayout> = 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)
}
}
}
}
}
}