I found a better solution using the new tool called ViewModel class. When the screen rotates, it automatically destroys de activity and creates it again, so we lost the focus of the last fragment selected. ViewModel helps us keeping the data and it's so useful for forms too.
- Create a class called
MainActivityViewModel.kt
Put this code inside:
class MainActivityViewModel : ViewModel() {
var menuItem : Int = R.id.nav_inicio
}
I'm choosing R.id.nav_inicio
as default menu item, modify it depending of your activity_main_drawer.xml (Default name for android studio)
3. Then, declare it into your MainActivity with the navigation drawer:
lateinit var vm : MainActivityViewModel
- Add this line into your onCreate override method:
vm = ViewModelProviders.of(this).get(MainActivityViewModel::class.java)
Then create a function that loads the default Fragment:
fun loadDefaultFragment() {
when (vm.menuItem) {
R.id.nav_inicio -> {
fab.hide()
val fragment = InicioFragment()
val manager = supportFragmentManager
manager.beginTransaction().replace(R.id.content_main, fragment, fragment.getTag()).commit()
}
R.id.nav_puntosventa -> {
fab.show()
val fragment = ListaPuntosFragment()
val manager = supportFragmentManager
manager.beginTransaction().replace(R.id.content_main, fragment, fragment.getTag()).commit()
}
else -> {
// default fragment if you consider necessary
}
}
}
this function must be called into your onCreate method after the initialization of the ViewModel.
6. Finally, we have to update the viewModel value each time we select a new menu item, so modify the override function onNavigationItemSelected adding it at the beginning:
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
vm.menuItem = item.itemId
// rest of the code ...
}
Now , when you rotate your screen, de viewmodel value save the position, you can use it with forms maybe.