Navigation drawers are the most common use android widget in android. The user can view the navigation drawer when they swipe the activity’s screen from the left edge of the android device. A user can also find it from the activity, by tapping the app icon (also known as the “hamburger” menu) in the action bar. DrawerLayout acts as a top-level container for window content that allows for interactive “drawer” views to be pulled out from one or both vertical edges of the window. Sometimes, our app requires a common navigation drawer for all activities in the app.
For implementing it, We can implement it by removing the same code from all activities and write it properly in our BaseActivity.
Please follow the steps in order to implement this functionality to complete this functionality:-
1. We have to add a navigation drawer and FrameLayout base_activity’s XML. You can go through the following screenshot.
2. Now we can initialize the navigation drawer in BaseActivity class like this:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = DataBindingUtil.setContentView(this, R.layout.activity_base) navigationView = mBinding?.navView toolbar = mBinding?.toolbar iv_menu = mBinding?.ivMenu drawerLayout = mBinding?.drawerLayout actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawerLayout?.setDrawerListener(actionBarDrawerToggle); // iv_menu?.setOnClickListener({ if (drawerLayout?.isDrawerOpen(GravityCompat.START)!!) { drawerLayout?.closeDrawer(GravityCompat.START) } else { drawerLayout?.openDrawer(GravityCompat.START) } }) } |
3. Now we can add all activity in that container of base activity. You can go through the code in the following snippet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class HomeActivity : BaseActivity(){ lateinit var mContentViewBinding: ActivityHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var contentFrameLayout = findViewById(R.id.content_frame) as FrameLayout mContentViewBinding = ActivityHomeBinding.inflate(layoutInflater) contentFrameLayout.addView(mContentViewBinding!!.root) mContentViewBinding.loading = true startInitialization() } } |
Just by following steps, We can achieve common navigation throughout activities in android. We can handle also handle click events from the base activity and add a handler on it.
We can also use the same approach for the common bottom tab bar.
I hope you enjoyed this blog and grab something new.
You can go through the following links in order to get more piece of information:-
https://developer.android.com/reference/android/widget/FrameLayout
https://material.io/components/navigation-drawer
Thanks for reading!!!