Jetpack Compose BasicTextField 占位符阻止在单击时获得焦点

问题描述 投票:0回答:2

我使用 Jetpack Compose BasicTextField 并使用文本组件设置占位符,如下所示:

当我单击占位符文本时,文本字段不会获得焦点。

这是 Compose 上的错误还是有任何解决方法?

代码是这样的:

                    BasicTextField(
                        value = "",
                        onValueChange = { input ->
                        },
                    ) { innerTextField ->
                        TextFieldDecorationBox(
                            value = "",
                            innerTextField = innerTextField,
                            placeholder = {
                                Text(
                                    text = "place holder"
                                )
                            },
                        )
                    }

提前致谢。

android android-jetpack-compose focus textfield
2个回答
0
投票

尝试为外部和内部文本字段设置相同的交互源。

val interactionSource = remember { MutableInteractionSource() }

BasicTextField(
    ...
    interactionSource = interactionSource
) { innerTextField ->
    OutlinedTextFieldDefaults.DecorationBox(
        ...
        interactionSource = interactionSource,
    )
}

-1
投票

我不确定,但可能你忘记调用

innerTextField()
中的
decoration box
函数,请检查下面的代码👇

@Composable
fun BasicTextFieldDesign() {

    var name by remember { mutableStateOf("") }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 20.dp),
        contentAlignment = Alignment.Center
    ) {
        BasicTextField(
            value = name,
            onValueChange = {
                name = it
            },
            decorationBox = { innerTextField ->
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .border(
                            width = 2.dp,
                            color = Color(0XFF4c8acc),
                            shape = RoundedCornerShape(10.dp)
                        )

                ) {
                    Row(
                        modifier = Modifier.padding(15.dp)
                    ) {
                        Icon(Icons.Outlined.Person, contentDescription = "")
                        if(name.isEmpty())
                        Text(text = "Enter name")
                        // you have to invoke this function then cursor will focus and you will able to write something
                        innerTextField.invoke()
                    }
                }
            }
        )
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.