如何将android撰写材料图标传递给textField

我想使用材质图标作为参数传递给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
    )
}
wwjazrael 回答:如何将android撰写材料图标传递给textField

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) }
    )
}
,

这可以使用 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)

结果如下:

enter image description here

本文链接:https://www.f2er.com/1477632.html

大家都在问