我是作曲新手,我主要是尝试按照教程来掌握各种组件。我有一个简单的函数,仅定义一个文本字段,如果添加一些参数,我将无法编译它。这是一个例子:
package com.example.jettip.components
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InputField(
modifier: Modifier = Modifier,
valueState: MutableState<String>,
labelId: String,
enabled: Boolean = true,
isSingleLine: Boolean = true,
keyboardType: KeyboardType = KeyboardType.Text,
imeAction: ImeAction = ImeAction.Default,
onAction: KeyboardActions = KeyboardActions.Default,
) {
var text by remember { mutableStateOf("") }
TextField(
value = valueState.value,
onValueChange = { text = it },
modifier = modifier,
enabled = enabled,
//keyboardType = keyboardType,
keyboardActions = onAction,
)
}
这编译得很好,但如果我取消注释 KeyboardType 参数,则会出现错误。
首先,这一行有一个错误:
onValueChange = { text = it },
“it”参数为红色,并显示错误“未解析的引用:it” 这对我来说毫无意义,除非我在 Studio 中配置了一些错误的东西
我还收到错误“没有任何函数可以使用提供的参数进行编译” 也许keyboardType需要使用另一个参数,但我无法从文档中看出。
我从 Studio 创建的一个空白活动项目开始。我有最新的工作室。我需要对我的 gradle 文件做些什么吗?
谢谢。
为此,它更像是一个有状态组件
var text by Remember { mutableStateOf("") }
如果你想使用它应该尝试一下:
{ valueState.value = it } // 对于委托
基于 Android 文档,它确实提到委托给调用者来更新它的值。
注意: 对于 M3 来说,它与 M2
没有太大区别它可能具有相同的名称,但可能需要另一个包装器。
针对 M3 尝试以下代码
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InputField(
modifier: Modifier = Modifier,
valueState: MutableState<String> = remember { mutableStateOf("") },
labelId: String,
enabled: Boolean = true,
isSingleLine: Boolean = true,
keyboardType: KeyboardType = KeyboardType.Text,
imeAction: ImeAction = ImeAction.Default,
onAction: KeyboardActions = KeyboardActions.Default,
) {
TextField(
value = valueState.value,
onValueChange = { valueState.value = it },
modifier = modifier,
enabled = enabled,
keyboardActions = onAction,
keyboardOptions = KeyboardOptions(keyboardType = keyboardType)
)
}