android – Add a button to the top right of action bar-ThrowExceptions

Exception or error:

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.

How to solve:

You can add a button by editing/create the menu xml file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""

        android:title="Text to be seen by user"


Then in your activity, if you created a new file your need to edit onCreateOptionsMenu

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(, menu);
    return true;

and you can edit what the actions do in the following method:

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 == {
        return true;

    return super.onOptionsItemSelected(item);


This might be easier, however I use a toolbar instead:

public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
            //your code
    return super.onOptionsItemSelected(item);

Leave a Reply

Your email address will not be published. Required fields are marked *