【问题标题】:How to pass android compose material icons to textField如何将android compose材质图标传递给textField
【发布时间】:2021-01-15 23:58:00
【问题描述】:

我想使用材质图标作为参数将它传递给 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
    )
}

【问题讨论】:

    标签: android google-material-icons android-compose-textfield


    【解决方案1】:

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

    结果如下所示:

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2018-07-17
        • 2022-06-11
        • 2019-12-14
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        • 1970-01-01
        相关资源
        最近更新 更多