Wednesday, May 16, 2012

13. Tutorial: ActionBar

13.1. Project

This chapter will demonstrate how to create items in the ActionBar and react to the selection of the user.
Create a project called "de.vogella.android.socialapp" with the Activity called "OverviewActivity".

13.2. 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 option "Menu", enter as File "mainmenu.xml" and press the button "Finish".
Creating a new XML resource for the menu
This will create a new file "mainmenu.xml" in the folder "res/menu" of your project. Open this file and select the "Layout" tab of the Android editor.
Press Add and select "Item". 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 set to "@+id/menuitem2", the Title 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 Activity class "OverviewActivity" 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

No comments:

Post a Comment