问题描述
我想使用材质图标作为参数传递给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
)
}
解决方法
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)
结果如下: