Search code examples
androidmenumenuitemoncreateoptionsmenu

Android onCreateOptionsMenu findItem get null


I'm new to android development. I created a new project with android studio default project template, Navigation Drawer Activity.

I added debug message as follow:

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

    MenuItem navCamera = menu.findItem(R.id.nav_camera);

    if(navCamera != null) {
        Log.d("MainActivity", "Not null");
    }

    return true;
}

Why I can't get the menu item object?

Main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />

activity_main_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_camera"
        android:icon="@drawable/ic_menu_camera"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />
</group>

<item android:title="Communicate">
    <menu>
        <item
            android:id="@+id/nav_share"
            android:icon="@drawable/ic_menu_share"
            android:title="Share" />
        <item
            android:id="@+id/nav_send"
            android:icon="@drawable/ic_menu_send"
            android:title="Send" />
    </menu>
</item>

</menu>

Solution

  • Sorry about above answer, I don't read your question exactly. You can find NavigationView in onCreate() and set icon using your lib

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        //other stuff here
        ...
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    
        // get menu from navigationView
        Menu menu = navigationView.getMenu();
    
        // find MenuItem you want to change
        MenuItem nav_camara = menu.findItem(R.id.nav_camara);
    
        // set new title to the MenuItem
        nav_camara.setTitle("NewTitleForCamera");
        // Set your icon menu here
    
        // do the same for other MenuItems
        ....
    
        // add NavigationItemSelectedListener to check the navigation clicks
        navigationView.setNavigationItemSelectedListener(this);
    
    }