Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
Mike Avatar asked Jul 01 '13 02:07

Mike


People also ask

Which method is used to create menu items on ActionBar?

The Android tooling automatically creates a reference to menu item entries in the R file, so that the menu resource can be accessed. An activity adds entries to the action bar in its onCreateOptionsMenu() method. The showAsAction attribute allows you to define how the action is displayed.


1 Answers

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.

like image 137
EGHDK Avatar answered Nov 08 '22 04:11

EGHDK