Home > Net >  Visual transformation for currency in compose
Visual transformation for currency in compose

Time:11-15

I would like to create a mask for TextField as $ NNNNNNNNNNNNNNNNNNNNN Where is the issue in my code? How to do it better? It does not erease all of the characters

class CurrencyMaskTransformation : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText = maskFilter(text)

    private fun maskFilter(text: AnnotatedString): TransformedText {
        // $ NNNNNNNNNNNNNNNNNNNNN
        var out = ""
        for (i in text.text.indices) {
            if (i == 0) out  = "$ "
            out  = text.text[i]
        }

        val numberOffsetTranslator = object : OffsetMapping {
            override fun originalToTransformed(offset: Int): Int {
                if (offset <= 0) return offset
                if (offset <= 2) return offset   1
                return text.text.length   2
            }

            override fun transformedToOriginal(offset: Int): Int {
                if (offset <= 0) return offset
                if (offset <= 2) return offset - 1
                return text.text.length
            }
        }

        return TransformedText(AnnotatedString(out), numberOffsetTranslator)
    }
}

EDIT:

val inputValue = remember { mutableStateOf(TextFieldValue("100")) }

            TextField(
                modifier = Modifier
                    .wrapContentWidth()
                    .height(64.dp),
                value = inputValue.value,
                onValueChange = {
                    inputValue.value = it
                },
                visualTransformation = CurrencyMaskTransformation()
            )

CodePudding user response:

If the pattern is $ NNNNNNNNNNNNNNNNNNNNN you should use as OffsetMapping something like;

    val numberOffsetTranslator = object : OffsetMapping {
        override fun originalToTransformed(offset: Int): Int {
            if (offset <= 0) return offset
            return text.text.length   2
        }

        override fun transformedToOriginal(offset: Int): Int {
            if (offset <= 2) return offset
            return offset -2
        }
    }

enter image description here

  • Related