I want my Textfield to be prefixed with a country code (+91), which can't be changed by the user. How do I achieve this?
You can use the visualTransformation
property:
Something like:
TextField(
value = text,
onValueChange = { text = it},
visualTransformation = PrefixTransformation("(+91)")
)
with:
class PrefixTransformation(val prefix: String) : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
return PrefixFilter(text, prefix)
}
}
fun PrefixFilter(number: AnnotatedString, prefix: String): TransformedText {
var out = prefix + number.text
val prefixOffset = prefix.length
val numberOffsetTranslator = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
return offset + prefixOffset
}
override fun transformedToOriginal(offset: Int): Int {
if (offset <= prefixOffset-1) return prefixOffset
return offset - prefixOffset
}
}
return TransformedText(AnnotatedString(out), numberOffsetTranslator)
}
You can simply add Text() inside leadingIcon parameter inside textField
OutlinedTextField(
value = text,
onValueChange = onTextChange,
maxLines = 1,
leadingIcon =
{
Text(
text = prefixText,
style = textStyle,
color = Color.Black,
modifier = Modifier.padding(start = 24.dp, end = 8.dp)
)
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With