【问题标题】:Why BasicTextField (in compose) doesn't work well?为什么 BasicTextField(在撰写中)不能很好地工作?
【发布时间】:2021-08-07 16:59:46
【问题描述】:

我正在尝试将BasicTextFieldTextAlignment.End 一起用于RTL。这是我的代码:

val textState = remember { mutableStateOf(TextFieldValue("")) }
val shape = RoundedCornerShape(CornerSize(4.dp))
BasicTextField(
    value = textState.value,
    onValueChange = { newText -> textState.value = newText },
    textStyle = LocalTextStyle.current.copy(
        color = ColorPrimaryDarkText,
        fontWeight = FontWeight.Medium,
        textAlign = TextAlign.End,
        fontSize = 14.sp,
    ),
    maxLines = 1,
    singleLine = true,
    modifier = Modifier
        .fillMaxWidth()
        .padding(32.dp, 0.dp)
        .clip(shape)
        .background(color = Color.White),
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Text,
        imeAction = ImeAction.Done
    ),

    decorationBox = { innerTextField ->
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White, shape)
                .padding(8.dp),
        ) {
            if (textState.value.text.isEmpty()) {
                Text(
                    text = "hint",
                    textAlign = TextAlign.End,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.fillMaxWidth(),
                    fontSize = 14.sp,
                )
            } else {
                innerTextField()
            }
        }
    }
)

它为空时可以,但是当您尝试输入任何内容时它就不能正常工作(它从中心开始输入):

【问题讨论】:

    标签: android kotlin android-jetpack android-jetpack-compose


    【解决方案1】:

    删除textAlign = TextAlign.End 并使用类似:

    CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl ) {
        BasicTextField( /* your code */)
    }
    

    否则,如果您想使用您的代码,请在Row 中添加horizontalArrangement = Arrangement.End decorationBox 参数:

        decorationBox = { innerTextField ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.White, shape)
                    .padding(8.dp),
                horizontalArrangement = Arrangement.End){
                  //your code
         }
    

    【讨论】:

    • 你能说一下为什么它不能很好地与TextAlign.End一起工作吗?
    • @HamidSj 将horizontalArrangement = Arrangement.End 添加到decorationBox 参数中的Row
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2013-12-22
    相关资源
    最近更新 更多