Android Menu

Menu’s are used to provide a familiar and consistent user experience, you should use the Menu  to present user actions and other options in your activities. such as searching for information, saving information, editing information, or navigating to a screen.

Types of menus:

Options menu and app bar :

Options menu: Appears in the app bar and provides the primary options that affect using the app itself. It’s  place where you should place actions that have a global impact on the app Examples of menu options: SearchBookmark and Settings to navigate to the Settings screen.

Context menu:

 Context menu Appears as a floating list of choices when the user performs a long tap on an element on the screen. It provides actions that affect the user selected content.

Examples of menu options: Edit to edit the element, Delete to delete it, and Share to share it over social media.

Contextual action bar:

Appears at the top of the screen overlaying the app bar, with action items that affect the selected element(s). and allows the user to select multiple options.  Examples of menu options: EditShare, and Delete for one or more selected elements.

A popup menu:

It displays a list of items in a vertical list that’s anchored to the view and  invoked the menu. It’s good for providing an overflow of actions that are relate to specific content or to provide options for a second part of a command means when we tap or click on the popup menu it performs specific action related to the anchor tag. Actions in a popup menu should not directly affect the corresponding content.

Example of a popup menu: the Gmail app anchors a popup menu to the app bar for the message view with ReplyReply All, and Forward.

The app bar and options menu:

The app bar is also called the action bar and it is a  dedicated space at the top of each activity screen. When we  create an activity from a template, an app bar is automatically created for the activity in a CoordinatorLayout root view group. The app bar by default shows the name of the app title, or the name defined in AndroidManifest.xml by the android:label attribute for the activity.

The options menu in the app bar provides navigation to other activities in the app,  For example, user selects options menu based on user choices for navigating to other activities, such as placing an order, or for actions that have a global impact on the app, such as changing settings or profile information, viewing order details.

Adding the app bar :

Each and every activity that uses the theme by default has an ActionBar as its app bar. Some themes also set up an ActionBar as an app bar by default. When you start an app from a template such as Empty Activity, even it also has an ActionBar appears as the app bar.

The android native ActionBar behaves differently depending on the version of Android running on the device. if you want to add an options menu for your app, you should use the “v7 appcompat support “library’s Toolbar as an app bar. Using the Toolbar we are making the availability of this menu that works on the widest range of devices.

Adding the support libraries:

Follow the below steps to add the dependencies for options menu :

Choose Tools > Android > SDK Manager to check that the Android Support Repository is installed; if not, install it. and then

Open the build.gradle file for your app, and add the support library feature project identifiers to the dependencies section. For example, to include support:appcompat and support:design, add:

compile 'com.android.support:appcompat-v7:23.4.0'

compile 'com.android.support:design:23.4.0

Note: In latest android version compile is replaced with implement

after adding the dependencies sync the build.gradle file to import all the dependencies that are required for options menu and make it available to the app.

Note: Update the version numbers for dependencies if necessary. If the version number you specified is lower than the currently available library version number, Android Studio will warn you (“a newer version of com.android.support:design is available”).

Using themes to design the app bar :

If you are creating an android project using the Basic Activity template, it adds the theme to replace the ActionBar with a Toolbar, so skip this step. If you are not using the Basic Activity template, then use the Toolbar class for the app bar by turning off the default ActionBar using a NoActionBar theme for the activity.

When we create a new project in Android Studio, an app theme is automatically generated.  For example, if you start an app project with the Empty Activity or Basic Activity template, the AppTheme created and  is provided in styles.xml in the res > values directory. We can also modify this styles.xml file according to the design.

Below example code for styles.xml file and we can modify it according to the requirement:

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
...
</resources>

AppTheme  it “inherits” all the styles from a parent theme

called Theme.AppCompat.Light.DarkActionBar

which is a standard theme supplied by Android. However, if we want to change the app bar then you can override an inherited style with another style by adding the other style to styles.xml file.

We will add styles under the theme below is the sample code to add the styles to the option bar

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
...
</style>

<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay"
parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay"
parent="ThemeOverlay.AppCompat.Light" /
>
...
</resources>

adding  the NoActionBar theme in AndroidManifest file:

<activity
...
android:theme="@style/AppTheme.NoActionBar">
</activity

By using above sample code application uses NoActionBar theme otherwise it uses default theme.

 

Adding AppBarLayout and a Toolbar to the layout :

 

If we create a basic android project  using basic template OR basic activity for this we can also  add AppbarLayout and Tool bar. we can include the   Toolbar in an activity’s layout by adding an AppBarLayout and a Toolbar element. AppBArLayout is a vertical LinearLayout and has many features

 

If we create a basic android project using basic template OR basic activity for this we can also add AppbarLayout and Tool bar. we can include the Toolbar in an activity’s layout file by adding an AppBarLayout and a Toolbar element in the xml file. AppBarLayout is a vertical LinearLayout and has many features

Below example describes how to add AppBarLayout under CordinateLayout in xml layout file.

<android.support.design.widget.CoordinatorLayout
... >
<android.support.design.widget.AppBarLayout
...>
<android.support.v7.widget.Toolbar
...
/>
</android.support.design.widget.AppBarLayout>
...
</android.support.design.widget.CoordinatorLayout>

If there is another  layout file, such as design_main.xml, we can include this layout file by using below code:

<include layout="@layout/design_main" />

we can set a scrolling behavior, for RelativeLayout group, to  an instance of  AppBarLayout.ScrollingViewBehavior  by using below sample code

<RelativeLayout
...
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
... >

</RelativeLayout>

Adding code to set up the app bar:

Follow the below code to add the layout file to the activity:

public class MyActivity extends AppCompatActivity {
...
}

Inside MainActivity class onCreate() implement this below sample code. we are loading Toolbar first then after we are calling  setSupportActionBar(toolbar);method it takes toolbar as input and executes it and set’s toolbar as actionbar for the activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}

This  setSupportActionBar(toolbar); method sets the toolbar as the appbar.

Adding the options menu :

Android provides a standard XML file format to define options menu items. This provides a facility to build menu’s separately and include them in your activity’s code, you can define the menu and all its items in an XML menu resource file. A menu resource defines (options menu, context menu, or popup menu) that can be inflated with MenuInflater, it loads resource as a  Menu object in your activity or fragment etc.

XML menu resource. Create an XML menu resource file for the menu items

Inflating the menu. To inflate the menu in your activity class override onCreateOptionsMenu() method.

Handling menu item clicks.

Menu items are views, so you can use the android:onClick attribute. The onOptionsItemSelected() method handles all the clickable events means when we click a menu item then at that time it performs specific task based on it.

Below sample xml code describes how to add menu items to the menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
...>
<item
android:id="@+id/action_settings"
android:title="@string/settings" />
</menu>

The below example sample code describes how to add more menu items to the menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
...>
<item
android:id="@+id/action_settings"
android:title="@string/settings" />
<item
android:id="@+id/action_order"
android:icon="@drawable/ic_order_white"
android:title="@string/action_order"/>
</menu>

Adding icons for menu items:

To add icons to the menu items first you need to save the images in the .jpg or .png format in to res/drawable folder and then follow the below sample code in xml file to add them.

<item
android:id="@+id/action_order"
android:icon="@drawable/ic_order_white"
android:title="@string/action_order"/>

 

Position attributes:

Position attribute is used to place the menu item based on their priority. for example lower the priority that will be placed first and higher the priority that will be placed last in the menu bar.

 

Menu Item orderInCategory attribute
MyOrder 5
MyStatus 15
MyFavorites 25
MyContact 50

 

Note: we also use 1, 2, 3, and 4 in the above example, the numbers 5, 15, 25, and 50 leave room  to add additional menu items in between them later whenever required

Inflating the menu resource Activity :

The getMenuInflater() method returns a  MenuInflater. The MenuInflater class provides the   infflate() method, which takes as a parameter the resource id for an XML layout resource file.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

Handling the menu item click :

this define android:onClick attribute means when button is clicked the method is executed and performs the specified task.

For example, you could define the MyFavorites item in the menu resource file to use the android:onClick  attribute to call the onMyFavoritesClick() method:

<item
android:id="@+id/action_myfavorites"
android:icon="@drawable/ic_myfavorites_white"
android:orderInCategory="40"
android:title="@string/action_myfavorites"
app:showAsAction="ifRoom"
android:onClick="onMyFavoritesClick" />

We are declaring the task inside this  onMyFavoritesClick() method in the activity class that will be performed or executed when user click on the onMyFavoritesClick():

public void onFavoritesClick(MenuItem item) {
// The item parameter indicates which item was clicked.
// Add code to handle the Favorites click.
}

The  onOptionsItemSelected() method of the Activities class handle all the menu item clicks in one place, and determine which menu item was clicked, which makes your code easier to understand and perform the specific task based on the clicked menu item

The below sample code describes how to add onOptionsItemSelected() method in activity class:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_order:
showOrder();
return true;
case R.id.action_status:
showStatus();
return true;
case R.id.action_contact:
showContact();
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}

 

Contextual menu :

Contextual menu  are used to allow  users to take an action on a selected view. we  can provide a context menu for any  View, Contextual menu are more often used for items in a  RecycleView, GridView, By using contextual menu the user can perform direct actions on each item.

Follow the below steps to create Contextual menu:

  • 1. Create an XML menu resource file for the menu items
  • 2. Register the context menu by  using the  registerForContextMenu() method of the Activity class.
  • 3. Implement the onCreateContextMenu() method in your activity class.
  • 4. Implement the onContextItemSelected() method in your activity to perform activity when
  •       it is clicked or selected.

Creating the XML resource file:

Create the XML menu resource directory and file . Use a suitable name for the file, such as menu_context. and then open it and Add the context menu items for that follow the below sample code to create menu items:

<item
android:id="@+id/context_myedit"
android:title="@string/myedit"
android:orderInCategory="50"/>

<item
android:id="@+id/context_myshare"
android:title="@string/myshare"
android:orderInCategory="80"/>

<item
android:id="@+id/context_mydelete"
android:title="@string/mydelete"
android:orderInCategory="90"/>

Registering a view to the context menu:

The below sample code used for registering the context menu by using  registerForContextMenu() method to the activity class.

Registering the  context menu for a view by using View.OnCreateContextMenuListener to this activity class.

onCreateContextMenu() will be called to show the context menu to the user or as a view.

We can show multiple views by using context menu. Each item in a ListView or GridView  provides the same context menu, register all items for a context menu by passing the ListView or GridView to registerForContextMenu().

...
// Registering the context menu to the text view of the article.
TextView article_text = (TextView) findViewById(R.id.article);
registerForContextMenu(article_text);
..

Creating onCreateContextMenu() method :

The below given sampe example describes how to implement onCreateContextMenu() method:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
}

The MenuInflater class has the inflate() method,  takes as a parameter the resource id for an XML layout resource to load menu_context  file in above example code.

Creating onContextItemSelected() method:

When user clicks the menu items then onContextItemSelected() method is called and executes or performs the respective menu items. dispays the view to the user.

@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_edit:
editNote();
return true;
case R.id.context_share:
shareNote();
return true;
default:
return super.onContextItemSelected(item);
}
}

Contextual action bar :

contextual action bar appears at the top of the screen to present actions when the user perform on a view action after long-clicking the view.

Follow the below steps to create Contextual action bar:

Creating the XML resource file:

<item
android:id="@+id/context_myedit"
android:orderInCategory="10"
android:icon="@drawable/ic_action_myedit_white"
android:title="@string/myedit" />

Setting the long-click listener:

Set up the contextual action bar listener in the onCreate() method, using View as the type for the view in order to use the setOnLongClickListener Inside Activity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
...
View articleView = findViewById(article);
articleView.setOnLongClickListener(new View.OnLongClickListener() {
...
// Add method here to start ActionMode after long-click.
...
});
}

Creating the ActionMode.Callback interface :

Before implementing onCreate() method to start ActionMode, we have to  implement the ActionMode.Callback interface to manage the action mode lifecycle. you can specify the actions for the contextual action bar by using call back methods, and respond to clicks on action items to perform.

Add the following method to the activity class (such as MainActivity) to implement the interface inside main activity class:

public ActionMode.Callback mActionModeCallback = new
ActionMode.Callback() {
...
// Add code to create action mode here.
...
}

Add the onCreateActionMode() code within the brackets of the above method to create action mode :

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
return true;
}

The onCreateActionMode() method inflates the menu using the same method used for a floating context menu. But  inflation occurs only when ActionMode is created, means when the user performs a long-click. The MenuInflater class provides the inflate() method, which takes as a parameter the resource id for an XML layout resource to load.

Add the onActionItemClicked() method with your handlers for each menu item:

When the menu item clicked then it executes onActionItemClicked(ActionMode mode, MenuItem item) method and performs the respective task and displays the view to the user.

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.context_edit:
editNote();
mode.finish();
return true;
case R.id.context_share:
shareNote();
mode.finish();
return true;
default:
return false;
}

Add these two methods to manage ActionModeLifeCycles  onPrepareActionMode() and onDestroyActionMode() methods:

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done.
}

The onPrepareActionMode() method shown above is called each time ActionMode occurs, and is always called after onCreateActionMode().

@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}

The complete example code for the ActionMode.Callback interface implementation for acticity class :

public ActionMode.Callback mActionModeCallback = new
ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
return true;
}

// Called each time ActionMode is shown. Always called after
// onCreateActionMode.
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}

// Called when the user selects a contextual menu item
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.context_edit:
editNote();
mode.finish();
return true;
case R.id.context_share:
shareNote();
mode.finish();
return true;
default:
return false;
}
}

// Called when the user exits the action mode
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};

Starting ActionMode:

When user performs a long-click to start action for that we have to startActionMode() to startActionMode() to perform the specific task based on the user’s long click.

@Override
protected void onCreate(Bundle savedInstanceState) {
...
articleView.setOnLongClickListener(new View.OnLongClickListener() {
// Called when the user long-clicks on articleView
public boolean onLongClick(View view) {
if (mActionMode != null) return false;
// Start the contextual action bar
// using the ActionMode.Callback.
mActionMode =
MainActivity.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}

The Sample example  code for the onCreate() method in the activity, along with  setOnLongClickListener()  and  startActionMode() given below:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// set up the contextual action bar listener
View articleView = findViewById(article);
articleView.setOnLongClickListener(new View.OnLongClickListener() {
// Called when the user long-clicks on articleView
public boolean onLongClick(View view) {
if (mActionMode != null) return false;
// Start the contextual action bar
// using the ActionMode.Callback.
mActionMode =
MainActivity.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}

Popup menu  :

A PopupMenu is a vertical list of items anchored to a View. It appears below the anchor view if there is room, or above the view otherwise.

Creating the XML resource file:

Use the below sample code to create popup button with image

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_popup"
android:src="@drawable/@drawable/ic_action_popup"/>

Creating onClickListener to the button in Activity class:

Create a member variable (mButton) in the activity’s class definition:

public class MainActivity extends AppCompatActivity {
private ImageButton mButton;
...
}

Asign the ImageButton in the layout file to the  onClickListener() in activity class

@Override
protected void onCreate(Bundle savedInstanceState) {
...
mButton = (ImageButton) findViewById(R.id.button_popup);
mButton.setOnClickListener(new View.OnClickListener() {
...
// define onClick here
...
});

Inflating the popup menu :

Here we are registering the popup menu with the

setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() to perform menu item clickabe action by the user.

@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, mButton);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.menu_popup, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {
...
// Add onMenuItemClick here
...
// Perform action here
...
}

Creating onMenuItemClick :

When user clicks popmenu item in the activity the the below code executes and performs the task displays the view to the user.

public boolean onMenuItemClick(MenuItem item) {
// Perform action here
return true;
}
});
popup.show(); //show the popup menu
}
});// close the setOnClickListener method

Use the above entire code inside  onCreate() method  of the activity class to create PopUp menu as shown in below example:

private ImageButton mButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
// popup button setup
mButton = (ImageButton) findViewById(R.id.button_popup);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, mButton);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.menu_popup, popup.getMenu());

//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Perform action here
return true;
}
});
popup.show();//show the popup menu
}
});//close the setOnClickListener method
}

Congratulations You Have Learned About Menu’s And It’s Creation In Android.

Leave a Reply

Categories