简体   繁体   中英

ActionBarSherlock requesting search

I`m trying to request search from ActionBarSherlock.

My class extends SherlockListActivity.

This is how I`m adding Menu button to the ActionBar:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Save")
            .setIcon(R.drawable.ic_action_search)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM |
                MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }

The problem is that I am unable to invoke it by id:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId())  {
            case ?????: {
                onSearchRequested();
                return true;
            }
        }
        return true;
    }

How people usually solve this problem?

Thanks.

If you inflate you menu from an XML menu file you will set an id which you can then use in your onOptionsItemSelected method. Like this:

XML

<menu xmlns:android="http://schemas.android.com/apk/res/android">     
    <item android:id="@+id/menu_search"
    android:icon="@drawable/ic_menu_search"
    android:showAsAction="ifRoom"
    android:actionViewClass="android.widget.SearchView" android:title="@string/search"/>
</menu>

Fragment

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.menu_search:
            onSearchRequested();

            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

Also you can use

 @Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {

    menu.add(0, 1, 1, "Refresh").setIcon(R.drawable.ic_refresh).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    menu.add(0, 2, 2, "Search").setIcon(R.drawable.ic_search).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

    return super.onCreateOptionsMenu(menu);
}


@Override
    public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
        switch (item.getItemId()){
            case 1:
                ...
                break;
            case 2:
                ...
                break;
        }
        return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM