Sorry to reply on an old post, but writing this because non of Stackoverflow solutions for my particular problem helped me.
If you are using new architecture components view model with a master detail shared view model and after returning from detail fragment get blank view pager, do the view model initialization in onViewCreated
method of master fragment and not in onCreate
(only needed in master fragment).
Also as other answers say remember to use childFragmentManager in view pager adapter.
like this:
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
class MasterFragment : Fragment() {
private lateinit var itemSelector: Selector
private lateinit var model: SharedViewModel
// In the master fragment do the view model initialization in onViewCreated
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
model = activity?.run {
ViewModelProviders.of(this).get(SharedViewModel::class.java)
} ?: throw Exception("Invalid Activity")
model.selected.observe(this, Observer<Item> { item ->
// Update the UI
})
}
}
class DetailFragment : Fragment() {
private lateinit var model: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this).get(SharedViewModel::class.java)
} ?: throw Exception("Invalid Activity")
model.selected.observe(this, Observer<Item> { item ->
// Update the UI
})
}
}