我有这个 TextField,我希望它从 Firestore 中的对象加载一个名称,然后我希望能够更改 Firestore 中的值和更新。我尝试了几种方法,但是当我加载该值时,我无法更改它或应用程序崩溃。
以下是我最后一次尝试,其中 textField (editText) 显示为空白。我需要在 textField 中加载 player.name 以便我可以更新它
@HiltViewModel
class ProfileViewModel @Inject constructor(
private val repository: PlayersRepository
) : ViewModel() {
var loading = mutableStateOf(false)
val data: MutableState<Player?> = mutableStateOf(null)
val editText = mutableStateOf(
data.value?.name ?: ""
)
init {
getUser()
}
fun onValueChanged(text: String){
this.editText.value = text
}
private fun getUser() {
loading.value = true
viewModelScope.launch {
val loggedUser = repository.getPlayerFromFirestore().data
loggedUser!!.addOnSuccessListener { document ->
val logged = document.toObject(Player::class.java)
data.value = logged!!
loading.value = false
}
}
}
@AndroidEntryPoint
class ProfileFragment : Fragment() {
private val viewModel: ProfileViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
val player = viewModel.data.value
selectedImageUri.value = player?.image?.toUri()
ReiDoFifaTheme {
if (player != null) {
OutlinedTextField(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(bottom = 16.dp),
value = editText,
onValueChange = { newValue ->
viewModel.onValueChanged(newValue)
}
)
另外,如何指定 textField 只接受正整数并将其限制为 2 位数字?