如何将android compose材质图标传递给textField

ccd*_*ccd 4 android google-material-icons android-compose-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
    )
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*uza 6

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) }
    )
}
Run Code Online (Sandbox Code Playgroud)