How to pass android compose material icons to textField

Viewed 2776

I want to use material icons as argument passing it to the 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
    )
}
2 Answers

The leadingIcon argument of texfield is a composable function (the label too), so one way to do it is:

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

This can be done using InlineTextContent. Here is an example how to insert the icon at the start of the text. You can wrap this into another composable if you just want to pass the icon as a parameter.

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)

The result would look like this:

enter image description here

Related