Sobes.tech
Junior — Middle

How can you ensure the preservation of user interface state within a fragment in a mobile app?

sobes.tech AI

Answer from AI

To preserve the user interface state in an Android fragment, the onSaveInstanceState(Bundle outState) method is usually used. In this method, you can save the necessary data into a Bundle, which is then restored in onViewCreated or onActivityCreated when the fragment is recreated.

Example:

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putString("key_text", editText.text.toString())
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    if (savedInstanceState != null) {
        val savedText = savedInstanceState.getString("key_text")
        editText.setText(savedText)
    }
}

You can also use ViewModel to store the state, which allows you to save data during configuration changes without needing to save it in a Bundle.

How can you ensure the preservation of user interface… - sobes.tech