Search code examples
androidkotlinfragmentnavigation-draweronclicklistener

Kotlin Drawer activity onclick event listner


I've started a new android project in Kotlin using the default Navigation Drawer Activity Minimum SDK api 28

My IDE is android studio 4.0.1

Then I run on my mobile to test. App compiles with success But I think click event listener is missing. Toggle menu works fine, but once click views never change, and can not find a way to switch between different menu's intent/fragments

I've found many different post about Navigation Drawer using onNavigationItemSelected, but none uses the latest version.

I've tried to implement onOptionsItemSelected, but can not find a clear doc for that

So if you can help me with that, I'll be grateful :)
... and sorry for my poor English

enter image description here Url repo on github => https://github.com/TVart/NavDrawerActivity


Solution

  • There's an ordering issue in the project template. In the activity_main.xml file, change

    <com.google.android.material.navigation.NavigationView
        ... />
    
    <include
        layout="@layout/app_bar_main"
        ... />
    

    to

    <include
        layout="@layout/app_bar_main"
        ... />
    <com.google.android.material.navigation.NavigationView
        ... />
    

    The example app should work after this. As to why the ordering matters, check out the official documentation for DrawerLayout: https://developer.android.com/reference/android/support/v4/widget/DrawerLayout

    Here is the important part:

    To use a DrawerLayout, position your primary content view as the first child with width and height of match_parent and no layout_gravity>. Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.