so I am new in MVVM and in Android in general, and I am little bit confused. it is said that to handle configuration change, I need to use MVVM to avoid data destruction due to configuration change.
but it seems that editText can save the data without using viewmodel. so I generate a random number and display it in editText and TextView like this in my fragment 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()
}
but the result is weird. say for example the generated number is 55, in portrait, both editText and TextView will show 55. when I rotate the device to landscape, the editText will still display 55, but the textView will show another number
so I have 2 questions:
is it a normal behaviour for editText to retain the value without using viewModel like this
Yes. Widgets with obvious user-mutable state will retain that state across configuration changes. That includes things like text in an EditText
and the checked state of CheckBox
and Switch
.
in this scenario, is it okay to not using viewmodel ?
Probably. Nothing in what you described would seem to require a viewmodel. In the end, you will need to adequately test the screen and confirm that everything works as it should after a configuration change.