Pipodi
Pipodi

Reputation: 49

How can I add an Action after clicking on an ActionBar's Button?

I want to add a new button to the ActionBar. When I click it, it does a specific Action. So I don't want a button that, after being pressed, opens a sub-menu (like the classic 3-dot menu).

I created a new button, this:

<item android:id="@+id/action_refresh"
      android:icon="@drawable/refresh"
      android:title="@string/refresh_string"
      android:showAsAction="always"/>

and it's shown on the ActionBar, but if I click it, naturally, it doesn't do anything.

How can I manage to get an Action just pressing it?

Thanks!

Upvotes: 1

Views: 213

Answers (2)

Michael Yaworski
Michael Yaworski

Reputation: 13483

Same as Homo sapiens's answer, but with an if-structure.

Add this method to your Activity class:

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    if (item.getItemId() == R.id.action_refresh) 
    {
        // do your stuff
        return true;
    }

    else if (item.getItemId() == R.id.otherItem) 
    { 
        // do other stuff
        return true;
    }

    // ...

   else 
   {
       return super.onOptionsItemSelected(item);
   }
}

Upvotes: 0

Subramanian Ramsundaram
Subramanian Ramsundaram

Reputation: 1347

You Need to override onOptionsItemSelected

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

Upvotes: 3

Related Questions