如何保存TextField JetpackCompose的可变状态



描述:

这是一个非常基本的问题,但我尝试了一些解决方案,但都不起作用。我只想在ViewModel中保存BasicTextField的状态。我尝试了mutableStateOf("SampleText"(,文本出现在BasicTextField中,但不可编辑,甚至键盘也没有出现

ViewModel代码:

@HiltViewModel
class NewWorkoutViewModel @Inject constructor(...) : ViewModel() {
var workoutTitle by mutableStateOf("")
...
}

屏幕代码:

@Composable
fun NewWorkoutScreen(
navController: NavController,
viewModel: NewWorkoutViewModel = hiltViewModel()
) {
Scaffold(...) { contentPadding ->
LazyColumn(...) {
item {
FillInContentBox(title = "Title:") {
//   TextField which is not working                   
BasicTextField(textStyle = TextStyle(fontSize = 20.sp),
value = viewModel.workoutTitle,
onValueChange ={viewModel.workoutTitle = it})
}
}
}
}
}

@Composable
fun FillInContentBox(title: String = "", content: @Composable () -> Unit = {}) {
Box(...) {
Column(...) {
Text(text = title)
content()
}
}
}

第二次尝试:

我也尝试过使用状态流,但仍然无法将文本编辑(填充(到TextField中。

ViewModel代码:

@HiltViewModel
class NewWorkoutViewModel @Inject constructor(...) : ViewModel() {
private val _workoutTitle = MutableStateFlow("")
var workoutTitle = _workoutTitle.asStateFlow()
fun setWorkoutTitle(workoutTitle: String){
_workoutTitle.value = workoutTitle
}
...
}

屏幕代码:

@Composable
fun NewWorkoutScreen(
navController: NavController,
viewModel: NewWorkoutViewModel = hiltViewModel()
) {
Scaffold(...) { contentPadding ->
LazyColumn(...) {
item {
FillInContentBox(title = "Title:") {
//   TextField which is not working                   
BasicTextField(textStyle = TextStyle(fontSize = 20.sp),
value = viewModel.workoutTitle.collectAsState().value,
onValueChange = viewModel::setWorkoutTitle)
}
}
}
}
}

@Composable
fun FillInContentBox(title: String = "", content: @Composable () -> Unit = {}) {
Box(...) {
Column(...) {
Text(text = title)
content()
}
}
}

您可以这样做:

在可组合中创建变量

var workoutTitle = remember{mutableStateOf("")}

在文本字段中传递变量值:

TextField(
value = workoutTitle.value,
onValueChange = {
/* You can store the value of your text view inside your
view model maybe as livedata object or state anything which suits you
*/
}
)