像Jetpack Compose中的Gmail一样,InputField中的芯片

3
我想知道在Jetpack Compose中是否有可能实现类似Gmail的行为,有人之前做过这样的事情并且愿意分享他们的解决方案吗?
我只想让用户在上传内容之前有机会添加标签,我不需要像下面gif中那样的弹出建议。
只需在InputField中使用简单的芯片即可。

回答你的问题。是的,这是可能的,这里有我的实现片段。我使用了最新的Jetpack Compose来构建这个可编辑的芯片组件https://streamable.com/3et0pg - Renz Carlo
@RenzCarlo 哇,这正是我想要的。 你介意分享你的代码并帮助我和其他开发者吗?目前还没有关于如何在Compose中实现可编辑芯片的资源。 - HavanaSun
1个回答

5
这是我做的方法。基本上,我只是使用了流行的行和一个文本字段。
KoohaHashTagEditor(
    textFieldValue = hashTagTextValue,
    onValueChanged = {
        hashTagError = null
        val values = FormUtil.splitPerSpaceOrNewLine(it.text)

        if (values.size >= 2) {
            if (!FormUtil.isFilled(values[0])) {
                hashTagError = "At least 2 characters per tag."
            } else if (!FormUtil.checkTagMinimumCharacter(values[0])) {
                hashTagError = "At least 2 characters per tag."
            } else if (!FormUtil.checkTagMaximumCharacter(values[0])) {
                hashTagError = "Up to 50 characters per tag."
            }

            if (hashTagError == null) {
                addHashTag(values[0])
                hashTagTextValue = hashTagTextValue.copy(text = "")
            }
        } else {
            hashTagTextValue = it
        }
    },
    focusRequester = hashTagFocusRequester,
    focusedFlow = hashTagFocusedFlow.value,
    textFieldInteraction = hashTagInteraction,
    label = null,
    placeholder = "To add a tag, hit the enter or space bar on your keypad after each tag.",
    rowInteraction = rowInteraction,
    errorMessage = hashTagError,
    listOfChips = uiState.hashtags,
    modifier = Modifier.onKeyEvent {
        if (it.key.keyCode == Key.Backspace.keyCode) {
            removeLastTag()
        }
        false
    },
    onChipClick = { chipIndex ->
        removeTagOnIndex(chipIndex)
    }
)

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun KoohaHashTagEditor(
    modifier: Modifier = Modifier,
    textFieldValue: TextFieldValue,
    onValueChanged: (TextFieldValue) -> Unit,
    focusRequester: FocusRequester,
    focusedFlow: Boolean,
    textFieldInteraction: MutableInteractionSource,
    label: String?,
    placeholder: String,
    readOnly: Boolean = false,
    message: String? = null,
    errorMessage: String? = null,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default.copy(
        keyboardType = KeyboardType.Text,
        imeAction = ImeAction.Default
    ),
    rowInteraction: MutableInteractionSource,
    listOfChips: List<String> = emptyList(),
    onChipClick: (Int) -> Unit
) {
    val isLight = MaterialTheme.colors.isLight

    val focusManager = LocalFocusManager.current
    val keyboardManager = LocalSoftwareKeyboardController.current

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .padding(
                vertical = 10.dp,
                horizontal = 20.dp
            )
            .clickable(
                indication = null,
                interactionSource = rowInteraction,
                onClick = {
                    focusRequester.requestFocus()
                    keyboardManager?.show()
                }
            )
    ) {

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
        ) {

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(),
                verticalArrangement = Arrangement.Center
            ) {

                if (label != null) {
                    Text(
                        text = "$label:",
                        style = MaterialTheme.typography.body1.copy(
                            fontWeight = FontWeight.Bold,
                            color = if (focusedFlow) MaterialTheme.colors.secondary else if (isLight) Color.Gray else Color.White
                        )
                    )
                }

                TextFieldContent(
                    textFieldValue = textFieldValue,
                    placeholder = placeholder,
                    onValueChanged = onValueChanged,
                    focusRequester = focusRequester,
                    textFieldInteraction = textFieldInteraction,
                    readOnly = readOnly,
                    keyboardOptions = keyboardOptions,
                    focusManager = focusManager,
                    listOfChips = listOfChips,
                    modifier = modifier,
                    emphasizePlaceHolder = false,
                    onChipClick = onChipClick
                )
            }

            ErrorSection(
                message = message,
                errorMessage = errorMessage
            )
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun TextFieldContent(
    textFieldValue: TextFieldValue,
    placeholder: String,
    onValueChanged: (TextFieldValue) -> Unit,
    focusRequester: FocusRequester,
    textFieldInteraction: MutableInteractionSource,
    readOnly: Boolean,
    keyboardOptions: KeyboardOptions,
    focusManager: FocusManager,
    listOfChips: List<String>,
    emphasizePlaceHolder: Boolean = false,
    modifier: Modifier,
    onChipClick: (Int) -> Unit
) {
    Box {
        val isFocused = textFieldInteraction.collectIsFocusedAsState()

        if (textFieldValue.text.isEmpty() && listOfChips.isEmpty()) {
            Text(
                text = placeholder,
                color = if (emphasizePlaceHolder && !isFocused.value) {
                    MaterialTheme.colors.onSurface
                } else {
                    if (MaterialTheme.colors.isLight) {
                        LocalCustomColors.current.muted
                    } else {
                        Color.Gray
                    }
                },
                modifier = Modifier.align(alignment = Alignment.CenterStart)
            )
        }

        FlowRow(
            modifier = Modifier
                .wrapContentHeight()
                .fillMaxWidth(),
            mainAxisSpacing = 5.dp
        ) {

            repeat(times = listOfChips.size) { index ->
                Chip(
                    onClick = { onChipClick(index) },
                    modifier = Modifier.wrapContentWidth(),
                    trailingIcon = {
                        Box(
                            modifier = Modifier
                                .clip(CircleShape)
                                .background(MaterialTheme.colors.primary)
                                .padding(3.dp)
                        ) {
                            Icon(
                                painter = rememberVectorPainter(image = Icons.Default.Close),
                                contentDescription = null,
                                modifier = Modifier.size(12.dp),
                                tint = if (MaterialTheme.colors.isLight) {
                                    Color.White
                                } else {
                                    Color.Black
                                }
                            )
                        }
                    },
                    colors = ChipDefaults
                        .chipColors(
                            backgroundColor = MaterialTheme.colors.secondary,
                            contentColor = MaterialTheme.colors.onSecondary
                        )
                ) {
                    Text(text = listOfChips[index])
                }
            }

            BasicTextField(
                value = textFieldValue,
                onValueChange = onValueChanged,
                modifier = modifier
                    .focusRequester(focusRequester)
                    .width(IntrinsicSize.Min),
                singleLine = false,
                textStyle = MaterialTheme.typography.body1.copy(color = MaterialTheme.colors.onSurface),
                decorationBox = { innerTextField ->
                    Row(
                        modifier = Modifier
                            .wrapContentWidth()
                            .defaultMinSize(minHeight = 48.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Start
                    ) {
                        Box(
                            modifier = Modifier.wrapContentWidth(),
                            contentAlignment = Alignment.CenterStart
                        ) {
                            Row(
                                modifier = Modifier
                                    .defaultMinSize(minWidth = 4.dp)
                                    .wrapContentWidth(),
                            ) {
                                innerTextField()
                            }
                        }
                    }
                },
                interactionSource = textFieldInteraction,
                cursorBrush = SolidColor(MaterialTheme.colors.secondary),
                readOnly = readOnly,
                keyboardOptions = keyboardOptions,
                keyboardActions = KeyboardActions(
                    onDone = {
                        focusManager.clearFocus()
                    }
                )
            )
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ErrorSection(
    message: String?,
    errorMessage: String?
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
    ) {

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            horizontalAlignment = Alignment.End
        ) {

            if (message != null) {
                val color = if (MaterialTheme.colors.isLight) {
                    Color.Gray
                } else {
                    Color.White
                }
                Text(
                    text = message,
                    fontStyle = FontStyle.Italic,
                    style = MaterialTheme.typography.body1.copy(color = color)
                )
            }
            if (errorMessage != null) {
                Chip(
                    onClick = {
                    },
                    colors = ChipDefaults
                        .chipColors(
                            backgroundColor = Color.Red,
                            contentColor = Color.White
                        ),
                    leadingIcon = {
                        Icon(
                            painter = rememberVectorPainter(image = Icons.Default.Info),
                            contentDescription = null
                        )
                    }
                ) {
                    Text(
                        text = errorMessage,
                        style = MaterialTheme.typography.body1.copy(fontSize = 12.sp),
                        modifier = Modifier.padding(2.dp)
                    )
                }
            }
        }
    }
}

非常感谢,您能否也提供记住变量,如hashTagTextValue、hashTagInteraction等。还有FormUtil类? - HavanaSun
我认为我提供的示例已经足够理解如何实现这样的组件,如果我回答了您的问题,请随意点击答案按钮,谢谢。 - Renz Carlo
是的,它正在工作,非常感谢。 填写缺失的部分有点困难,但对于不是 Jetpack Compose 初学者的人来说,这是一个非常有帮助的答案。 - HavanaSun
@RenzCarlo,你能帮忙填写一下吗?我无法想出如何做。或者分享一些你已经完成的代码库给我参考吗? - TheRock
@RenzCarlo 请提供存储库链接。 - Manmohan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接