How to pass android compose material icons to textField

8.6k views Asked by At

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

There are 3 answers

0
Nando On

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

0
Thiago Souza On

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) }
    )
}
0
codejockie On

As @Nando showed using an Image, you can do the same using an Icon from Material UI.

Text(text = buildAnnotatedString {
            appendInlineContent("icon", "icon")
            append(text)
        },
            inlineContent = mapOf(
                Pair("icon", InlineTextContent(
                    Placeholder(
                        width = 1.7.em,
                        height = 23.sp,
                        placeholderVerticalAlign = PlaceholderVerticalAlign.TextTop
                    )
                ) {
                    Icon(
                        Icon(Icons.Rounded.Person),
                        contentDescription = null,
                        tint = Color.Blue
                    )
                }
                )),
            lineHeight = 23.sp,
            fontSize = 14.sp,
            fontWeight = FontWeight.Normal)