Search code examples
androidandroid-actionbar

How to enable back press button on the right side of action bar?


I would like to add a back arrow button to the right side of action bar.

I have the following code, but it adds the back button to the the left side of the action bar.

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true); 

Solution

  • What you did is enabled the action-bar's back functionality on click/touch event. If you want a button at the right of the action bar, the best/easy thing you can do is to add an overflow menu, for which you can set-up any icon you want.

    There are lots of tutorials on how to do this (for ex. http://www.techotopia.com/index.php/Creating_and_Managing_Overflow_Menus_on_Android).

    Essential points are as follows.

    1. Create the layout/items for the overflow menu (filename should match with the one in the 2nd step).

      <menu xmlns:android="http://schemas.android.com/apk/res/android" >  
              <item  
                      android:id="@+id/menu_settings"  
                      android:orderInCategory="1"  
                      android:showAsAction="never"  
                      android:icon="@drawable/overflow_menu_icon"  
                      android:title="@string/menu_settings" />  
      </menu>  
      
    2. Init the overflow inside the onCreateOptionsMenu() function, where activity_menu_app is the name of the .xml file created in the previous step.

      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
              getMenuInflater().inflate(R.menu.activity_menu_app, menu);
              return true;
      }
      
    3. Catch the touch events of the menu items inside onOptionsItemSelected() function.

      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
              switch (item.getItemId()) {
                      case R.id.menu_settings:
                              // do your stuff here
                              return true;
                      default:
                              return super.onOptionsItemSelected(item);
              }
      }