kotlin 如何在Android Compose中的输入字段的右下角添加字符计数器?

bvjxkvbb  于 2023-11-21  发布在  Kotlin
关注(0)|答案(1)|浏览(170)

我试图在我的Android应用程序中添加常规输入字段与撰写的帮助.所以我希望我的输入字段显示在右侧有多少个字符离开,他可以添加.例如,它以0/100开始.然后他开始键入单词“你好”和计数器显示5/100
它应该显示在输入字段的内部。有什么方法可以实现吗?
与xml中的app:counterEnabled =“true”等效

sh7euo9m

sh7euo9m1#

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackExampleTheme {
                var textValue by remember { mutableStateOf(TextFieldValue()) }
                CustomTextField(
                    value = textValue,
                    onValueChange = { textValue = it },
                    maxCharacters = 100,
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CustomTextField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit,
    maxCharacters: Int,
    modifier: Modifier = Modifier
) {
    var charCount by remember(value) { mutableStateOf(value.text.length) }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        TextField(
            modifier = modifier
                .fillMaxWidth()
                .height(50.dp),
            value = value,
            onValueChange = {
                if (it.text.length <= maxCharacters) {
                    onValueChange(it)
                    charCount = it.text.length
                }
            },
        )

        Text(
            text = "$charCount/$maxCharacters",
            modifier = Modifier
                .height(20.dp)
                .wrapContentWidth()
                .align(Alignment.End),
            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
            fontSize = 12.sp
        )
    }
}

@Composable
@Preview(showBackground = true)
fun CharCountTextFieldPreview() {
    Surface(
        modifier = Modifier
            .padding(16.dp)
            .height(70.dp)
    ) {
        var textValue by remember { mutableStateOf(TextFieldValue()) }
        CustomTextField(
            value = textValue,
            onValueChange = { textValue = it },
            maxCharacters = 100,
            modifier = Modifier.fillMaxWidth()
        )
    }
}

字符串
为预览添加此构建.gradle

implementation 'androidx.compose.ui:ui-tooling-preview'

相关问题