0

I was exploring one of the navigation samples provided by Android here. Here each of bottom nav items has a nested graph of their own.

  1. Currently I'm on the Second tab (Leaderboard) and on changing the tab, onDestroy() of the fragment gets called and on switching back to same tab, the onCreate() of fragment gets called. Does that mean the fragment state is not saved and restored on tab switching? As per my understanding, fragment states are saved and restored, but how is that being insured / implemented if the onDestroy is called?

  2. On navgation using back button or findNavController().navigateUp() same lifecycle states gets called, but this time fragment state is not restored when you switch back. Can we avoid that somehow?

This is the Leaderboard fragment which I'm using to debug the lifecycle states.

class Leaderboard : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_leaderboard, container, false)

        val viewAdapter = MyAdapter(Array(10) { "Person ${it + 1}" })

        view.findViewById<RecyclerView>(R.id.leaderboard_list).run {
            // use this setting to improve performance if you know that changes
            // in content do not change the layout size of the RecyclerView
            setHasFixedSize(true)

            // specify an viewAdapter (see also next example)
            adapter = viewAdapter

        }
        return view
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("Log", "onCreate")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("Log", "onDestroy")
    }
}```
  • I know that starting with jetpack navigation 2.4.0 multi back stacks are supported by default when we use bottom navigation using setUpWithNavController. But the lifecycle of these fragments is confusing on the tab switch. Please let me know in case any clarifying question is required – Saurabh Jaiswal May 10 '23 at 12:46

0 Answers0