Skip to content

Instantly share code, notes, and snippets.

@RicardAparicio
Last active March 2, 2022 17:09
Show Gist options
  • Save RicardAparicio/bdd6cd30410f9431e1da238202a1dfa9 to your computer and use it in GitHub Desktop.
Save RicardAparicio/bdd6cd30410f9431e1da238202a1dfa9 to your computer and use it in GitHub Desktop.
Obfuscation / Hiding text with TransformationMethod
import android.graphics.Rect
import android.text.method.TransformationMethod
import android.view.View
class ObfuscationTransformation(val type: Type) : TransformationMethod {
enum class Type {
Email, Phone
}
override fun getTransformation(source: CharSequence, view: View?): CharSequence {
return PassCharSequence(source, type)
}
override fun onFocusChanged(
view: View?,
sourceText: CharSequence?,
focused: Boolean,
direction: Int,
previouslyFocusedRect: Rect?
) {
/* noop */
}
private class PassCharSequence(private val charSequence: CharSequence, private val type: Type) :
CharSequence {
override val length: Int
get() = charSequence.length
override fun get(index: Int): Char {
return getChar(index)
}
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
return PassCharSequence(charSequence.substring(startIndex, endIndex), type)
}
private fun getChar(index: Int): Char {
return when (type) {
Type.Email -> {
val atIdx = charSequence.indexOf("@")
when {
index < atIdx -> {
when (index != 0 && index < atIdx - 1) {
true -> "*".single()
false -> charSequence[index]
}
}
index > atIdx -> {
val dotIdx = charSequence.indexOfLast { char -> char == ".".single() }
when (index > atIdx + 1 && index < dotIdx - 1) {
true -> "*".single()
false -> charSequence[index]
}
}
else -> charSequence[index]
}
}
Type.Phone -> {
when(index > charSequence.length - (charSequence.length - 1) && index < charSequence.length - 2) {
true -> "*".single()
false -> charSequence[index]
}
}
}
}
}
}
@RicardAparicio
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment