Single activity app with Navigation Component and Navigation Drawer

1.4k Views Asked by At

I want to create a Single Activity app which will contain for simplicity only the following screens: Landing, Login, Register, Home, Profile. The Home and Profile screens will be visible to the user only if is logged in and will belong to a Navigation Drawer.

Unfortunately what comes to my mind is to create an Activity with nav_graph_1, that contains the following destinations: Landing, Login, Register. Then create another Activity with nav_graph_2 (Home and Profile destinations) that will contain all the setup for the Navigation Drawer: e.g. setupActionBarWithNavController, appBarConfiguration with the nav_graph_2 and the drawer.

Is it possible to implement the above in a Single Activity app and how?

1

There are 1 best solutions below

1
On

Is it possible to implement the above in a Single Activity app and how?

Short Answer: yes, it's possible.

Long Answer:

what comes to my mind is to create an Activity with nav_graph_1, that contains the following destinations: Landing, Login, Register. Then create another Activity with nav_graph_2 (Home and Profile destinations) that will contain all the setup for the Navigation Drawer

I assume that your main issue for having a single activity model: is that you have a container that you suggested to be as your second activity because of having sub-containers in it (Drawer fragments). You can do that if you wish, but you can also use a single activity and multiple fragments arranged in cascaded nav graphs like in below navigation graph scheme.

enter image description here

  • The landing fragment is considered the root fragment of your activity.
  • Your activity layout has a FragmentContainerView that can host login register, and main fragments
  • After the user login, you switch to the main fragment
  • Like the main activity layout, the main fragment layout just has a FragmentContainerView for its sub-fragments. Where you can create a new navigation graph for it which contains Home and Profile fragments.

Here you have 2 navigation graph, the first contains 4 fragments (landing, login, register, and main), and the other contains 2 fragments (home and profile).

So, your in your example you've 2 navigation graphs:

Graph 1

enter image description here

Graph 2

enter image description here