Adding Action Bar

Web Hosting
In this tutorial, I will show you how to add action bar in android. See Sample below.


First thing I did is, adding this code below in your menu folder under res folder.

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="Search"
          android:showAsAction="ifRoom" />
    
    <item android:id="@+id/action_refresh"
          android:icon="@drawable/ic_refresh"
          android:title="Refresh"
          android:showAsAction="ifRoom" />
    
     <item android:id="@+id/action_help"
          android:icon="@drawable/ic_help"
          android:title="Help"
          android:showAsAction="ifRoom" />
    
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:showAsAction="never" />

</menu>

Next is adding the needed images in your drawable folder in different densities. After that, go to your main activity.java and add this code below.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.your, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   // Handle presses on the action bar items
   switch (item.getItemId()) {
       case R.id.action_search:
        Toast.makeText(getApplicationContext(), "Searching........", Toast.LENGTH_SHORT).show();
           return true;
       case R.id.action_refresh:
        Toast.makeText(getApplicationContext(), "Refreshing........", Toast.LENGTH_SHORT).show();
           return true;
       case R.id.action_help:
        Toast.makeText(getApplicationContext(), "Helping........", Toast.LENGTH_SHORT).show();
           return true;
       default:
           return super.onOptionsItemSelected(item);
   }
}

Web Hosting
That's it, Hope this may help you.

No comments:

Post a Comment