Mike Mike - 1 month ago 25
Android Question

actionbar menu item onclick?

I have an action bar that puts everything in a menu in the top right, which the user clicks and the menu options open up.

I inflate the action bar menu with this on each activity I use it:

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

return true;
}


And my xml for main2.xml is:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
android:id="@+id/action_searchHome"
android:orderInCategory="100"
android:showAsAction="never"
android:title="Seach"/>



</menu>


My question is do I put an onclick in the item in the xml and if so where do I put the onclick method it calls? Do I need to put it in every activity I launch this action bar in?

Answer

If you add an onClick attribute on your menu item like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_searchHome"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:onClick="doThis"
        android:title="Seach"/>



</menu>

Then in your activity:

public void doThis(MenuItem item){
    Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
}

Note:

ActionBarSherlock is deprecated. Unless you are developing an app for Android 4.0 or older, please don't use it. But if you are using the library, you will have to import

import com.actionbarsherlock.view.MenuItem;

and not

import com.android.view.MenuItem;

In addition, you could do something like this: ActionBar Sherlock Menu Item OnClick

which @adneal mentions.