How to perform action on Actionbar icon?

Total Post:27

Points:189
 1157  View(s)
Ratings:
Rate this:
Actionbar icon in android
  1. Post:28

    Points:196
    Re: How to perform action on Actionbar icon?

    Add menu  in res/menu/main_activity_actions.xml

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
        <!-- Search, should appear as action button -->
        <item android:id="@+id/action_search"
              android:icon="@drawable/ic_action_search"
              android:title="@string/action_search"
              android:showAsAction="ifRoom" />
        <!-- Settings, should always be in the overflow -->
        <item android:id="@+id/action_settings"
              android:title="@string/action_settings"
              android:showAsAction="never" />
    </menu>

    Use this override method

    // This method will show menu in action bar
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

     And now again use below override method

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_search:// your code here      
                return true;
            case R.id.action_settings:// your code here      
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

      Modified On Apr-06-2018 06:16:02 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!