Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prefix country code in Textfield using Jetpack Compose

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?

like image 270
Sparsh Dutta Avatar asked May 28 '21 08:05

Sparsh Dutta


2 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

like image 131
Gabriele Mariotti Avatar answered Sep 18 '22 20:09

Gabriele Mariotti


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)
        )
    }
)
like image 38
Amr Avatar answered Sep 17 '22 20:09

Amr