Add Optionsmenu To Toolbar

Posted on

Modify from final instance of “Set title, subtitle together with logo of Toolbar“, to add OptionsMenu to Toolbar.


Create /res/menu/menu_main.xml to define our OptionsMenu.

<?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">     <item         android:id="@+id/menu_camera"         android:icon="@android:drawable/ic_menu_camera"         android:orderInCategory="100"         android:title="Add OptionsMenu to Toolbar"         app:showAsAction="always"/>     <item         android:id="@+id/menu_compass"         android:icon="@android:drawable/ic_menu_compass"         android:orderInCategory="100"         android:title="Add OptionsMenu to Toolbar"         app:showAsAction="always"/>     <item         android:id="@+id/menu_agenda"         android:icon="@android:drawable/ic_menu_agenda"         android:orderInCategory="100"         android:title="Add OptionsMenu to Toolbar"         app:showAsAction="always"/>     <item         android:id="@+id/menu_gallery"         android:icon="@android:drawable/ic_menu_gallery"         android:orderInCategory="100"         android:title="Add OptionsMenu to Toolbar"         app:showAsAction="always"/>     <item         android:id="@+id/menu_calendar"         android:icon="@android:drawable/ic_menu_my_calendar"         android:orderInCategory="100"         android:title="Add OptionsMenu to Toolbar"         app:showAsAction="always"/> </menu> 

Modify MainActivity.java, override onCreateOptionsMenu() together with onOptionsItemSelected().

package com.blogspot.android_er.androidtoolbar;  import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast;  populace cast MainActivity extends AppCompatActivity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          getSupportActionBar().setTitle("Toolbar example");         toolbar.setSubtitle(".blogspot.com");         toolbar.setLogo(android.R.drawable.ic_menu_info_details);      }      @Override     populace boolean onCreateOptionsMenu(Menu menu) {         getMenuInflater().inflate(R.menu.menu_main, menu);         provide super.onCreateOptionsMenu(menu);     }      @Override     populace boolean onOptionsItemSelected(MenuItem item) {         Toast.makeText(this, item.getTitle(), Toast.LENGTH_LONG).show();         provide super.onOptionsItemSelected(item);     } }  

Next:
– Set picture on Toolbar