Android - SPLessons

Android Action Bar

Chapter 6

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android Action Bar

Android Action Bar

Android Action Bar, also known as the App Bar, is used to maintain consistency in navigation across the application. It performs various actions like adapting to screen configurations (landscape & portrait), prioritizing list of actions, adding widgets to action bar (search, sharing etc.), supporting navigation between screens (drop-down & tabbed navigation) and much more. In this chapter, we will explain you about the functionality of Action Bar.

The Android Action Bar is located at the top of the screen. It can display the activity title, icon, and actions which can be triggered, viewed, etc. The Action Bar is added in API Level 11. Applications with a target SDK version below API Level 11 can use the option menu provided the button is present on the device.

The option menu will be displayed when a user presses the Option button.

The activity bar is superior to the options menu, because the action bar is clearly visible, while the options menu can be seen only upon request.

Entries in the Action Bar

• Entries in the action bar are called actions, which are defined in an XML resource file and are saved under res/menu folder. The Android tooling automatically creates a reference to this file in the R file so as to access the menu resource.

Creating Actions

An activity adds entries to the action bar in its onCreateOptionsMenu()method.
• The MenuInflator class allows to inflate actions defined in an XML file and adds them to the ActionBar. MenuInflator can be accessed via the getMenuInflator() method from your activity.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- display always -->
<item android:id="@+id/action_info"
android:icon="@drawable/info"
android:title="info"
android:showAsAction="always"/>
</menu>

The <item> element has several attributes that can be used to define an item’s behavior and appearance. The attributes of an item are:

Values for showAsAction are:

ifRoom: Place this item in the Action Bar only if there is room for it.
withText: Also include the title text (defined by android:title) with the action item. You can include this value along with one of the others as a flag set, by separating them with a pipe |.
never: Never place this item in the Action Bar.
always: Always place this item in the Action Bar. Try to avoid setting multiple items to always appear as action items as it can result in them overlapping with other UI in the action bar.
collapseActionView: The action view associated with this action item (as declared by android:actionLayout or android: actionViewClass) is collapsible. Introduced in API Level 14.

• On selecting an action

If an action is selected, the onOptionsItemSelected() method in the corresponding activity is called. It receives the selected action as a parameter. Based on this information, the following operations can be done.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_contact:
// contact
Toast.makeText(getApplicationContext(), "you clicked on contact us", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_info:
// info
Toast.makeText(getApplicationContext(), "you clicked on info", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

• Customizing the action bar

1. To customize an ActionBar. For Example: hide and show action bar.

ActionBar actionBar = getActionBar();
actionBar.hide();
actionBar.show();

2. To Enable Up / Back navigation:

actionBar.setDisplayHomeAsUpEnabled(true);

Declare parent activity in manifest as

<activity
…………………………..
android:parentActivityName="com.spl.myproject.ParentActivity">
</activity>

On clicking the Icon, you will navigate to parent activity.

3.To change the text displayed along the side of an application icon at runtime, the following action should be performed:

ActionBar actionBar = getActionBar();
actionBar.setTitle("SPLessons");

4. To change the background of an ActionBar, the following action should be performed:

ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(Drawable d) ;

5.To set an activity to a full screen mode:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

6. Addition of search widget, spinner to action bar and Tab Navigation is explained in the Android TabLayout chapter.

The following example explains how to use an ActionBar.

Create MainActivity.java under  src/<your package name>

MainActivity.java:


public class MainActivity extends Activity {

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

        /*// customizing action bar-&amp;amp;amp;amp;amp;gt;get action bar (added in API Level 11)
             ActionBar actionBar = getActionBar();

            // Enabling Up / Back navigation
            actionBar.setDisplayHomeAsUpEnabled(true);
            */
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Take appropriate action for each action item click
        switch (item.getItemId()) {
            case R.id.action_contact:
                // contact
                Toast.makeText(getApplicationContext(), "you clicked on contact us", Toast.LENGTH_SHORT).show();

                return true;
            case R.id.action_info:
                // info
                Toast.makeText(getApplicationContext(), "you clicked on info", Toast.LENGTH_SHORT).show();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

Create activity_main.xml under res/layout folder

activity_main.xml:

&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     
                xmlns:tools="http://schemas.android.com/tools"     
				android:layout_width="match_parent"     
				android:layout_height="match_parent"     
				tools:context=".MainActivity" &gt;

    &lt;TextView   android:layout_width="wrap_content"         
	            android:layout_height="wrap_content"         
				android:layout_centerHorizontal="true"         
				android:layout_centerVertical="true"         
				android:textColor="#009ACD"         
				android:text="ActionBar Example" /&gt;
&lt;/RelativeLayout&gt;

Create main.xml under res/menu folder

main.xml:

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt;
    &lt;!-- display always --&gt;
    &lt;item android:id="@+id/action_info"   
	      android:icon="@drawable/info"           
		  android:title="info"           
		  android:showAsAction="always"/&gt;

    &lt;!--show if room is available --&gt;
    &lt;item android:id="@+id/action_message"           
	      android:icon="@drawable/message"           
		  android:title="message"           
		  android:showAsAction="ifRoom" /&gt;

    &lt;!--show with text --&gt;
    &lt;item android:id="@+id/action_contact"           
	      android:icon="@drawable/contactus"           
		  android:title="contact us"           
		  android:showAsAction="withText" /&gt;

    &lt;!--never display this --&gt;
    &lt;item android:id="@+id/action_help"           
	      android:icon="@drawable/help"           
		  android:title="help"           
		  android:showAsAction="never"/&gt;

&lt;/menu&gt;

AndroidManifest.xml:

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.spl.myproject"
    android:versionCode="1"
    android:versionName="1.0" &gt;

    &lt;uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="16" /&gt;

    &lt;application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" &gt;
        &lt;activity
            android:name="com.spl.myproject.MainActivity"
            android:label="@string/app_name" &gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;

                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
            &lt;/intent-filter&gt;

       &lt;/activity&gt;
    &lt;/application&gt;

&lt;/manifest&gt;

Output: