Search code examples
javaandroidkotlinnavigation-drawersample

How to add an item to Android Studio's Navigation Drawer template and set Listener for it?


I cant find where is navigationView.setNavigationItemSelectedListener used in that sample. I want to link that item to a fragment like what's done on the template! Is there any other way to set setNavigationItemSelectedListener without overriding this method?


Solution

  • You use

    navigationView.setNavigationItemSelectedListener(this);
    

    inside onCreate. And to answer your question I don't think so.

    YourActivity implements NavigationView.OnNavigationItemSelectedListener {...}
    

    Inside onCreate

    //handle drawer logic
    
        navigationView.setNavigationItemSelectedListener(this);
    

    Then the navigation listener

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            use item.getItemId to handle the clicks
    drawer.closeDrawer(GravityCompat.START);
            return true;
        }
    

    Check for and close the drawer in OnBackPressed as well. I'm assuming you know how to load your fragment.

    The default template at least on Android Studio 4.0.1 uses Navigation Component, which is meant to replace the implementation you meant in your question and the one I showed. So If you want to use navigation component refer to this link