How to create common Activity with Navigation Menu and Toolbar

Hey Folks!! In this tutorial we are going to learn how to create a common activity with toolbar and navigation menu that can be used for all the activities in your android project. We’ll be using a new kind of activity called Bottom Navigation Activity as our Base(Common) Activity. So, let’s get started.

1. Create a new android project, add a Bottom Navigation Activity and rename the Activity’s name as ‘BaseActivity’ and layout name as “activity_base.xml”.

2. Open the activity_base.xml layout and design a layout as below.

3. Now, add the following code in your BaseActivity abstract class. In this class, we have created five methods:
(i) initBaseActivityView() : for initializing the Base Activity’s views.
(ii) setBaseActivityFonts() : for setting the fonts in Base Activity’s views.
(iii) setView(int viewLayout, String activityTitle) : to be used by activity which extends BaseActivity class for setting the content view. We need to pass the viewLayout for the activity and the title for that activity. Title will be displayed on the toolbar.
(iv) abstract initViews() and abstract setFonts(): for initializing child activitiy’s views and setting the fonts for views.

4. Let’s see how to use our BaseActivity in other activities. Create a new Empty activity and name it as “MainActivity” and its layout as activity_main. The layout will be look like below.

5. Open MainActivity class and make it extend our BaseActivity class by replacing AppCompatActivity(or Activity) by BaseActivity. It should ask for implementing the abstract methods initViews() and setFonts(). Implement those two methods and go to onCreate() method. Replace the setContentView() line with setView(, ).

6. Create a new layout resource file for navigation list, name it as navigation_listview.xml and add the following code.

7. Create a new layout resource file for navigation header, name it as navigation_header.xml and add the following code.

8. Create a menu resource file, name it as navigation.xml and add the following code.

9. Run the App.

Please drop a comment below if you face any issues.

Download the complete project

admin Author

Leave a Reply

Your email address will not be published. Required fields are marked *