1

我想使用材质图标作为将其传递给 textField 的参数。

@Composable
fun NormalTextField(
    icon: () -> Unit,  // how to pass material icon to textField
    label: String
) {
    val (text, setText) = mutableStateOf("")
    TextField(
        leadingIcon = icon,
        value = text,
        onValueChange = setText,
        label = label
    )
}
4

2 回答 2

3

texfield 的leadingIcon 参数是一个可组合的函数(标签也是),所以一种方法是:

@Composable
fun Example() {
    NormalTextField(label = "Email") {
        Icon(
            imageVector = Icons.Outlined.Email,
            contentDescription = null
        )
    }
}

@Composable
fun NormalTextField(
    label: String,
    Icon: @Composable (() -> Unit)
) {
    val (text, setText) = mutableStateOf("")
    TextField(
        leadingIcon = Icon,
        value = text,
        onValueChange = setText,
        label = { Text(text = label) }
    )
}
于 2021-07-30T15:24:15.480 回答
1

这可以使用InlineTextContent来完成。这是一个如何在文本开头插入图标的示例。如果您只想将图标作为参数传递,则可以将其包装到另一个可组合项中。

Text(text = buildAnnotatedString {
    appendInlineContent("photoIcon", "photoIcon")
    append("very long breaking text very long breaking text very long breaking text very long breaking text very long breaking text")
}, inlineContent = mapOf(
    Pair("photoIcon", InlineTextContent(
        Placeholder(width = 1.7.em, height = 23.sp, placeholderVerticalAlign = PlaceholderVerticalAlign.TextTop)
    ) {
        Image(
            painterResource(R.drawable.ic_cameraicon),"play",
            modifier = Modifier.fillMaxWidth().padding(end = 10.dp),
            alignment = Alignment.Center,
            contentScale = ContentScale.FillWidth)
    }
)), lineHeight = 23.sp, color = Color.White, fontFamily = HelveticaNeue, fontSize = 18.sp, fontWeight = FontWeight.Medium)

结果将如下所示:

在此处输入图像描述

于 2021-05-06T16:28:50.033 回答