Is there a way I can add a button to the top right of my ActionBar, like where the default settings Button is? I removed the settings Button but I'd like to add a custom Button in it's place.
            Asked
            
        
        
            Active
            
        
            Viewed 5.8k times
        
    26
            
            
        2 Answers
72
            You can add a button by editing/create the menu xml file:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_name"
        android:icon="@drawable/you_resource_here"
        android:title="Text to be seen by user"
        app:showAsAction="always"
        android:orderInCategory="0"/>
</menu>
Then in your activity, if you created a new file your need to edit onCreateOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
and you can edit what the actions do in the following method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_name) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
- 
                    Thanks! I will try this in a bit and return – Brejuro Jul 13 '15 at 15:29
 - 
                    Sorry, I know this is late, but for some reason nothing happens when I click on the button. Is there some other code I need to add? – Larry Jing Jun 12 '18 at 21:04
 - 
                    1If you're seeing the icon appear in the ActionBar, then clicking it should work with what's written above. Try adding a Toast/log line to the first line of onOptionsItemSelected, the issue could be somewhere else. – Android Jun 13 '18 at 23:53
 
3
            
            
        This might be easier, however I use a toolbar instead:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_name:
            //your code
            break;
    }
    return super.onOptionsItemSelected(item);
}
        Dennis van Opstal
        
- 1,294
 - 1
 - 22
 - 44
 
        Arpit todewale
        
- 153
 - 12