Search code examples
androidkotlinandroid-edittextandroid-architecture-componentsandroid-viewmodel

does edittext retain the data when configuration change ? do I need view model if I only have edittext in my screen?


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:

  1. is it a normal behaviour for editText to retain the value without using viewModel like this ?
  2. I have 2 editText and a button in my fragment. the user just input the data to those 2 editText, and when the button is pressed, it just past the input value to the next screen. there is no business logic, input validation or networking at all. in this scenario, is it okay to not using viewmodel ?

Solution

  • 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.