How to prefix country code in Textfield using Jetpack Compose

Viewed 1597

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?

3 Answers

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)
}

enter image description here

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)
        )
    }
)

Another option you could use as well as Gabriele's answer is using the leadingIcon property of TextField

TextField(
    value = text,
    onValueChange = { text = it},
    leadingIcon = {
                Icon(
                    painter = painterResource(id = R.drawable.ic_pound_symbol),
                    contentDescription = null,
                    tint = colorResourceFromAttr(id = R.attr.colorOnSurface)
                )
            }
)

Which gives you this:

a jetpack compose textfield with pound symbol prefix

Related