Android Action Bar Example Code - Android

How to handle action bar in android?

Snippet Code

Rate this page :
  [ 0 votes]

Android action bar is a application which performs some actions and provide navigation which helps to an create elegant user interfaces. Steps to create action bar in android are:
Remove default action bar in your file to add new action bar.
Create activity_main_actions.xml file under res-->menu.
Next,to make an interactions for the item. You need to open your main activity and then override onOptionsItemSelected() method. Selected action for item can be identified by using it’s id.

activity_main_actions.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="" > <!-- Search / will display always --> <item android:id="@ id/action_search" android:icon="@drawable/ic_action_search" android:title="@string/action_search" android:showAsAction="ifRoom"/> <!-- Location Found --> <item android:id="@ id/action_location_found" android:icon="@drawable/ic_action_location_found" android:title="@string/action_location_found" android:showAsAction="ifRoom" /> <!-- Refresh --> <item android:id="@ id/action_refresh" android:icon="@drawable/ic_action_refresh" android:title="@string/action_refresh" android:showAsAction="ifRoom" /> <!-- Help --> <item android:id="@ id/action_help" android:icon="@drawable/ic_action_help" android:title="@string/action_help" android:showAsAction="never"/> <!-- Check updates --> <item android:id="@ id/action_check_updates" android:icon="@drawable/ic_action_refresh" android:title="@string/action_check_updates" android:showAsAction="never" /> </menu> override onOptionsItemSelected() method: public class MainActivity extends Activity{ /** * On selecting action bar icons * */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Take appropriate action for each action item click switch (item.getItemId()) { case // search action return true; case // location found LocationFound(); return true; case // refresh return true; case // help action return true; case // check for updates action return true; default: return super.onOptionsItemSelected(item); } } /** * Launching new activity * */ private void LocationFound() { Intent i = new Intent(MainActivity.this, LocationFound.class); startActivity(i); } }


Ask Questions

Ask Question