Skip to content

Instantly share code, notes, and snippets.

@dmersiyanov
Last active July 24, 2020 16:15
Show Gist options
  • Save dmersiyanov/2b8f6f9472969fc0dd23749ec8f5c8f0 to your computer and use it in GitHub Desktop.
Save dmersiyanov/2b8f6f9472969fc0dd23749ec8f5c8f0 to your computer and use it in GitHub Desktop.
Handy solution to support non-removable prefix for https://github.com/RedMadRobot/input-mask-android library
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.redmadrobot.inputmask.MaskedTextChangedListener
import com.redmadrobot.inputmask.helper.AffinityCalculationStrategy
import com.redmadrobot.inputmask.model.Notation
class NonRemovePrefixTextChangedListener(
primaryFormat: String,
affineFormats: List<String> = emptyList(),
customNotations: List<Notation> = emptyList(),
affinityCalculationStrategy: AffinityCalculationStrategy = AffinityCalculationStrategy.WHOLE_STRING,
autocomplete: Boolean = true,
autoskip: Boolean = false,
val field: EditText,
listener: TextWatcher? = null,
valueListener: ValueListener? = null,
private val nonRemovePrefix: String
) : MaskedTextChangedListener(
primaryFormat,
affineFormats,
customNotations,
affinityCalculationStrategy,
autocomplete,
autoskip,
field,
listener,
valueListener
) {
override fun afterTextChanged(edit: Editable?) {
val text = field.text.toString()
if (!text.startsWith(nonRemovePrefix)) {
setText(nonRemovePrefix, field)
} else {
super.afterTextChanged(edit)
}
}
companion object {
fun installOn(
editText: EditText,
primaryFormat: String,
affineFormats: List<String> = emptyList(),
customNotations: List<Notation> = emptyList(),
affinityCalculationStrategy: AffinityCalculationStrategy = AffinityCalculationStrategy.WHOLE_STRING,
autocomplete: Boolean = true,
autoskip: Boolean = false,
listener: TextWatcher? = null,
valueListener: ValueListener? = null,
nonRemovePrefix: String
): NonRemovePrefixTextChangedListener {
val maskedListener = NonRemovePrefixTextChangedListener(
primaryFormat,
affineFormats,
customNotations,
affinityCalculationStrategy,
autocomplete,
autoskip,
editText,
listener,
valueListener,
nonRemovePrefix
)
editText.addTextChangedListener(maskedListener)
editText.onFocusChangeListener = maskedListener
return maskedListener
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment