Sunday, July 22, 2012

OptionMenu and ActionBar

,

ActionBar

The ActionBar is located at the top of the Activity that may display the Activity title, navigation modes, and other interactive items.
The following picture show the ActionBar of a typical Google Application with interactive items and a nagivation bar.

ActionBar Screenshot

OptionsMenu

The application can also open a menu which shows actions via a popup menu. This OptionsMenu is only available if the phone has a hardware "Options" button. Even if the hardware button is available, it is recommended to use the ActionBar, which is available for phones as of Android 4.0.
The following picture highlights the hardware button and the resulting menu as popup.

Old OptionsMenu

One of the reasons why the ActionBar is superior to the OptionsMenu, if that it is clearly visible, while the OptionsMenu is only shown on request and the user may not recognize that options are available.

Creating the menu

The OptionsMenu and the ActionBar is filled by the onCreateOptionsMenu() method of your Activity.
In the onCreateOptionsMenu() method you can create the menu entries. You can add menu entries via code or via the inflation of an existing XML resources.
The MenuInflator class allows to inflate menu entries defined in XML to the menu. MenuInflator can get accessed via the getMenuInflator() method in your Activity.
The onCreateOptionsMenu() method is only called once. If you want to influence the menu later you have to use the onPrepareOptionsMenu() method. onPrepareOptionsMenu() is not called for entries in the ActionBar for these entries you have to use the invalidateOptionsMenu() method.

Reacting to menu entry selection

If a menu entry is selected then the onOptionsItemSelected() method is called. As parameter you receive the menu entry which was selected so that you can react differently to different menu entries.

Using the home icon

The ActionBar also shows an icon of your application. You can also add an action to this icon. If you select this icon the onOptionsItemSelected() method will be called with the value android.R.id.home. The recommendation is to return to the main Activity in your program.

// If home icon is clicked return to main Activity
case android.R.id.home:
 Intent intent = new Intent(this, OverviewActivity.class);
 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);
 break; 

ActionBar tabs

It is also possible to add tabs to the ActionBar which can be used for navigation. Typically Fragments are used for this purpose. We demonstrate this in the Fragments chapter.

Custom Views in the ActionBar

You can also add a custom View to the ActionBar. The following code snippet demonstrates that.

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 
 ActionBar actionBar = getActionBar();
 // add the custom view to the action bar
 actionBar.setCustomView(R.layout.actionbar_view);
 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
  | ActionBar.DISPLAY_SHOW_HOME);
} 

Contextual action mode

A contextual action mode activates a temporary ActionBar that overlays the application ActionBar for the duration of a particular sub-task.
The contextual action mode is typically activated by selecting an item or by long clicking on it.
To implemented this, call the startActionMode() method on a View or on your Activity. This method gets an ActionMode.Callback object which is responsible for the lifecycle of the contextual ActionBar.

Context menus

You can also assign a context menu to a View. A context menu is also activated if the user "long presses" the view.
If possible the contextual action mode should be preferred over a context menu.
A context menu for a view is registered via the registerForContextMenu(view) method. The onCreateContextMenu() method is called every time a context menu is activated as the context menu is discarded after its usage. The Android platform may also add options to your View, e.g. EditText provides context options to select text, etc.


===   Tutorial: ActionBar   ===

Project


Create a project called "de.vogella.android.socialapp" with the Activity called OverviewActivity.

Add a menu XML resource

Select your project, right click on it and select NewOtherAndroidAndroid XML File to create a new XML resource.
Select the Menu option, enter mainmenu.xml as filename and press the Finish button.

Creating a new XML resource for the menu

This will create a new mainmenu.xml file in the res/menu folder of your project. Open this file and select the Layout tab of the Android editor.
Press the Add button and select the Item entry. Maintain a entry similar to the following screenshot. Via the ifRoom attribute you define that the menu entry is displayed in the ActionBar if there is sufficient space available.

How to maintain the menu entries in an menu xml file

Add a similar entry to the menu with the ID attribute set to "@+id/menuitem2", and the Title attribute set to "Test". Also set the ifRoom flag.
The resulting XML will look like the following.

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

    <item
        android:id="@+id/menuitem1"
        android:showAsAction="ifRoom"
        android:title="Prefs">
    </item>
    <item
        android:id="@+id/menuitem2"
        android:showAsAction="ifRoom"
        android:title="Test">
    </item>

</menu> 

Change your OverviewActivity class to the following.

package de.vogella.android.socialapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class OverviewActivity extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
  case R.id.menuitem1:
   Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT)
     .show();
   break;
  case R.id.menuitem2:
   Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT)
     .show();
   break;

  default:
   break;
  }

  return true;
 }
} 

Run your application. As there is enough space in the ActionBar otherwise you may see the Overflow menu or you have to use the Option menu button on your phone. If you select one item, you should see a small info message.

Social App running

Tutorial: Using the contextual action mode

Add a EditText element your main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/myView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

</LinearLayout> 

Create a new menu XML resource with the file name "contextual.xml"

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/toast"
        android:title="Toast">
    </item>

</menu> 

Change your Activity to the following.

package de.vogella.android.socialapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class OverviewActivity extends Activity {
 protected Object mActionMode;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  // Define the contextual action mode
  View view = findViewById(R.id.myView);
  view.setOnLongClickListener(new View.OnLongClickListener() {
   // Called when the user long-clicks on someView
   public boolean onLongClick(View view) {
    if (mActionMode != null) {
     return false;
    }

    // Start the CAB using the ActionMode.Callback defined above
    mActionMode = OverviewActivity.this
      .startActionMode(mActionModeCallback);
    view.setSelected(true);
    return true;
   }
  });
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  Toast.makeText(this, "Just a test", Toast.LENGTH_SHORT).show();
  return true;
 }

 private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

  // Called when the action mode is created; startActionMode() was called
  public boolean onCreateActionMode(ActionMode mode, Menu menu) {
   // Inflate a menu resource providing context menu items
   MenuInflater inflater = mode.getMenuInflater();
   // Assumes that you have "contexual.xml" menu resources
   inflater.inflate(R.menu.contextual, menu);
   return true;
  }

  // Called each time the action mode is shown. Always called after
  // onCreateActionMode, but
  // may be called multiple times if the mode is invalidated.
  public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
   return false; // Return false if nothing is done
  }

  // Called when the user selects a contextual menu item
  public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
   switch (item.getItemId()) {
   case R.id.toast:
    Toast.makeText(OverviewActivity.this, "Selected menu",
      Toast.LENGTH_LONG).show();
    mode.finish(); // Action picked, so close the CAB
    return true;
   default:
    return false;
   }
  }

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

} 

If you run this example and long press the EditText widget, your contextual ActionBar is displayed.

Contextual ActionBar demonstrated

(vogella.com)

0 comments to “OptionMenu and ActionBar”

Post a Comment

 

Android Development Tutorials Copyright © 2011 -- Template created by O Pregador -- Powered by Blogger Templates