Skip to content Skip to sidebar Skip to footer

Android: Actionbar Item Onclick

1-To add a search item to my actionbar i have the item in this way: onOptionsItemSelected like so:

@OverridepublicbooleanonOptionsItemSelected(MenuItem item){
    switch(item.getItemId()){
    case R.id.search:
        // your action goes herereturntrue;
        default:
            returnsuper.onOptionsItemSelected(item);
    }
}

And inflate your layout into the ActionBar as the following:

@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mymenu, menu);
    returntrue;
}

2.ifRoom means place the action item on the action bar if there is space. However, space is determined by the following: less than half the width of the action bar horizontal space and the count is less than the max number of action items - Jake Wharton.

Have a look here for more information on the android ActionBar

Solution 2:

The way to process action bar clicks in your Activity is as following:

@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
    finalintid= item.getItemId();
    if (R.id.search == id) {
        // do something and maybe return true...
    }
    returnsuper.onOptionsItemSelected(item);
}

The ifRoom tag means that if there's not enough room for the item in the action bar, it will appear in the action overflow.

Solution 3:

ActionBar Menu items are created using

@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);

    returntrue;
}

And then the click events of the items are delivered using

@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.search:
        //TODO do your thing.returntrue;
    default:
        returnfalse;
    }
}

One more thing, ifRoom means that the item is displayed as an icon if there is room. If you have only one item, there is a room always. If there is not room, the item is displayed in overflow menu.

Solution 4:

You need to follow the complete tutorial as mentioned in that LINK

and ifRoom tag means: the specified item will be visible only if there is space available on the action bar.

And dont use onClick listener in this senario, onOptionItemSelected will be perfect. Its all well documented in the mentioned link.

Solution 5:

  1. In your Activity click of menu item will be handeled here. .

@Override

publicbooleanonOptionsItemSelected(MenuItem item) {
 // Handle presses on the action bar itemsswitch (item.getItemId()) {
           case R.id.search:
           //do your work herereturntrue;    
            }
        }

2. android:showAsAction

Keyword. When and how this item should appear as an action item in the Action Bar. A menu item can appear as an action item only when the activity includes an ActionBar

ifRoom Only place this item in the Action Bar if there is room for it.

you can get details here

Post a Comment for "Android: Actionbar Item Onclick"