配置更改时 edittext 是否保留数据?如果我的屏幕上只有编辑文本,我还需要视图模型吗?
does edittext retain the data when configuration change ? do I need view model if I only have edittext in my screen?
所以我是 MVVM 和 Android 的新手,我有点困惑。据说为了处理配置变更,我需要使用MVVM来避免配置变更导致的数据破坏。
不过好像editText不用viewmodel也能保存数据。所以我生成一个随机数并在我的片段 onCreate
.
中像这样在 editText 和 TextView 中显示它
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// generate random number
val min = 20
val max = 80
val random = Random().nextInt((max - min) + 1) + min
testEditText.setText(random.toString())
testTextView.text = random.toString()
}
但结果很奇怪。例如生成的数字是 55,在纵向模式下,editText 和 TextView 都会显示 55。当我将设备旋转到横向时,editText 仍会显示 55,但 textView 会显示另一个数字
所以我有两个问题:
- editText 在不使用 viewModel 的情况下保留值是正常行为吗?
- 我的片段中有 2 个 editText 和一个按钮。用户只需将数据输入到这 2 个 editText 中,当按下按钮时,它只是将输入值传递到下一个屏幕。根本没有业务逻辑、输入验证或网络。在这种情况下,不使用 viewmodel 可以吗?
is it a normal behaviour for editText to retain the value without using viewModel like this
是的。具有明显用户可变状态的小部件将在配置更改时保留该状态。这包括 EditText
中的文本以及 CheckBox
和 Switch
的选中状态。
in this scenario, is it okay to not using viewmodel ?
可能吧。您所描述的内容似乎都不需要视图模型。最后,您需要充分测试屏幕并确认配置更改后一切正常。
所以我是 MVVM 和 Android 的新手,我有点困惑。据说为了处理配置变更,我需要使用MVVM来避免配置变更导致的数据破坏。
不过好像editText不用viewmodel也能保存数据。所以我生成一个随机数并在我的片段 onCreate
.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// generate random number
val min = 20
val max = 80
val random = Random().nextInt((max - min) + 1) + min
testEditText.setText(random.toString())
testTextView.text = random.toString()
}
但结果很奇怪。例如生成的数字是 55,在纵向模式下,editText 和 TextView 都会显示 55。当我将设备旋转到横向时,editText 仍会显示 55,但 textView 会显示另一个数字
所以我有两个问题:
- editText 在不使用 viewModel 的情况下保留值是正常行为吗?
- 我的片段中有 2 个 editText 和一个按钮。用户只需将数据输入到这 2 个 editText 中,当按下按钮时,它只是将输入值传递到下一个屏幕。根本没有业务逻辑、输入验证或网络。在这种情况下,不使用 viewmodel 可以吗?
is it a normal behaviour for editText to retain the value without using viewModel like this
是的。具有明显用户可变状态的小部件将在配置更改时保留该状态。这包括 EditText
中的文本以及 CheckBox
和 Switch
的选中状态。
in this scenario, is it okay to not using viewmodel ?
可能吧。您所描述的内容似乎都不需要视图模型。最后,您需要充分测试屏幕并确认配置更改后一切正常。