【问题标题】:How to set the inputType for a TextField in Jetpack Compose如何在 Jetpack Compose 中为 TextField 设置 inputType
【发布时间】:2021-03-04 20:23:09
【问题描述】:

我想限制用户可以在 Jetpack Compose 的 TextField 中键入的内容。我该怎么做?

xml中的等价物是inputType:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:hint="Only numbers please!" />

【问题讨论】:

    标签: android android-jetpack-compose android-compose-textfield


    【解决方案1】:

    使用KeyboardOptions:

    TextField(
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
    

    【讨论】:

    • 如果 {,.-} 不是必须的(keyboardType = KeyboardType.NumberPassword)可以使用
    【解决方案2】:

    你可以使用类似的东西:

    TextField(
            ....,
            keyboardOptions = 
                 KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number)
            )
    

    【讨论】:

    • 复制默认有什么好处?
    • @Sergey 优点是只覆盖一个值。
    【解决方案3】:

    像这样KeyboardOptions

    var textShopName by remember { mutableStateOf("") } 
    
    OutlinedTextField(
                keyboardOptions = KeyboardOptions(
                    capitalization = KeyboardCapitalization.None,
                    autoCorrect = true,
                    keyboardType = KeyboardType.Number,
                    imeAction = ImeAction.Next
                ),
                value = textShopName,
                onValueChange = { textShopName = it },
                label = { Text("Shop Name") },
                modifier = Modifier
                    .padding(start = 16.dp, end = 16.dp, top = 20.dp)
                    .fillMaxWidth(),
    
                )
    

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多