Create Menu

👉menu_items.xml


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

  //app:showAsAction: never for showing title only.

    <item
        android:id="@+id/action_insert_dummy_data"
        android:title="Insert dummy note"
        android:icon="@drawable/ic_insert"
        app:showAsAction="never" />

     // app:showAsAction: always for showing icon only.
    <item
        android:id="@+id/action_delete_all_entries"
        android:title="Delete all notes"
        app:showAsAction="always" />
</menu>

👉MainActivity.java


public class MainActivity extends AppCompatActivity {

  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
          if (mCurrentNoteUri == null) {
          
          //Setting Activity title
            setTitle("Add New Note");
            
            // Invalidate the options menu, 
           // so the "Delete" menu option can be hidden.
           
           // =>For hinding menu call invalidateOptionsMenu(); and 
          // set visibility => false in onPrepareOptionsMenu();
           
            invalidateOptionsMenu();
        } else {
            //Setting Activity title
            setTitle("Edit Note");
        }



    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu options from the res/menu/menu_catalog.xml file.
        // This adds menu items to the app bar.
        getMenuInflater().inflate(R.menu.menu_catalog, menu);
        return true;
    }
    
    //For hiding menu
    
     @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        // If this is a new pet, hide the "Delete" menu item.
        if (mCurrentNoteUri == null) {
            MenuItem menuItem = menu.findItem(R.id.action_delete);
            menuItem.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // User clicked on a menu option in the app bar overflow menu
        switch (item.getItemId()) {
            // Respond to a click on the "Insert dummy data" menu option
            case R.id.action_insert_dummy_data:
                insertPet();
                return true;
            // Respond to a click on the "Delete all entries" menu option
            case R.id.action_delete_all_entries:
                showDeleteConfirmationDialog();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }