Skip to content

Instantly share code, notes, and snippets.

@mnafian
Created May 17, 2019 06:34
Show Gist options
  • Save mnafian/f9132bc2d7b6373769f3dad3e62ea1c4 to your computer and use it in GitHub Desktop.
Save mnafian/f9132bc2d7b6373769f3dad3e62ea1c4 to your computer and use it in GitHub Desktop.
textWatcher(object : TextWatcher {
private val mArray_pos: IntArray = intArrayOf(3)
private var mBeforeTextChanged: CharSequence = ""
private val mAppentText: String = "-"
override fun afterTextChanged(s: Editable) {
for (i in mArray_pos.indices) {
if (mBeforeTextChanged.length - mAppentText.length * i == mArray_pos[i] - 1 && s.length - mAppentText.length * i == mArray_pos[i]) {
s.append(mAppentText)
break
}
if (mBeforeTextChanged.length - mAppentText.length * i == mArray_pos[i] && s.length - mAppentText.length * i == mArray_pos[i] + 1) {
val idx_start = mArray_pos[i] + mAppentText.length * i
val idx_end = Math.min(idx_start + mAppentText.length, s.length)
val sub = s.toString().substring(idx_start, idx_end)
if (sub != mAppentText) {
s.insert(s.length - 1, mAppentText)
}
break
}
if (mAppentText.length > 1 &&
mBeforeTextChanged.length - mAppentText.length * i == mArray_pos[i] + mAppentText.length &&
s.length - mAppentText.length * i == mArray_pos[i] + mAppentText.length - 1
) {
val idx_start = mArray_pos[i] + mAppentText.length * i
val idx_end = Math.min(idx_start + mAppentText.length, s.length)
s.delete(idx_start, idx_end)
break
}
if (s.toString().isNotBlank() && s.toString().length == 7) {
viewModel.setStateProp(claimCode = s.toString())
}
}
}
override fun beforeTextChanged(
s: CharSequence, start: Int,
count: Int, after: Int
) {
mBeforeTextChanged = s.toString()
}
override fun onTextChanged(
s: CharSequence, start: Int,
before: Int, count: Int
) {
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment