0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jetpack Composeでテキスト入力欄にPrefix, Suffixを入れる

Posted at

本文

主にAndroid開発でKotlinのJetpack Composeで入力欄にprefix, suffixを付ける方法。
たとえば、金額入力欄に
「料金1000円」
と入力させたいときに、ユーザーには数値のみを入力させ、最初の「料金」(prefix)と最後の「円」(suffix)を自動で付加できる。

FormText.kt
OutlinedTextField(
    visualTransformation = PreSuffixTransformer("料金", "円"),
    label = {
        Text("お会計")
    },
)

class PreSuffixTransformer(val prefix: String = "", val suffix: String = "") : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        val result = AnnotatedString(prefix, spanStyle = SpanStyle(Color.Gray)) + text + AnnotatedString(suffix, spanStyle = SpanStyle(Color.Gray))

        val offsetMapping = object : OffsetMapping {
            override fun originalToTransformed(offset: Int) =
                offset + prefix.length
            override fun transformedToOriginal(offset: Int) =
                if(text.length < offset){ text.length } else { offset }
        }
        return TransformedText(result, offsetMapping)
    }
}

参考

【Jetpack Compose】TextFieldの表示形式変換機能の活用例5選
https://mixi-developers.mixi.co.jp/compose-textfield-visualtransformation-d17cfd0980ed

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?