Search code examples
androidbuttonandroid-actionbar

How to add button in ActionBar(Android)?


I want to add a Button to the Action Bar to the right hand side of Example as in this screen shot:

a screenshot of an actionbar with no buttons. the title is 'Example'

I get actionBar in onCreate method as:

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

and back button(onOptionsItemSelected method) as below:

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(),MainActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}

How can I add button?


Solution

  • you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.yourentry, menu);
        return true;
    }
    

    an entry for the menu could be:

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
        <item
            android:id="@+id/action_cart"
            android:icon="@drawable/cart"
            android:orderInCategory="100"
            android:showAsAction="always"/> 
    </menu>