Example usage for android.view MenuItem setOnActionExpandListener

List of usage examples for android.view MenuItem setOnActionExpandListener

Introduction

In this page you can find the example usage for android.view MenuItem setOnActionExpandListener.

Prototype

public MenuItem setOnActionExpandListener(OnActionExpandListener listener);

Source Link

Document

Set an OnActionExpandListener on this menu item to be notified when the associated action view is expanded or collapsed.

Usage

From source file:co.carlosjimenez.android.currencyalerts.app.MenuTint.java

/**
 * <p>Sets a ColorFilter and/or alpha on all the {@link MenuItem}s in the menu, including the
 * OverflowMenuButton.</p>//  w w w .  j  a  v a2 s  .co m
 * <p/>
 * <p>Call this method after inflating/creating your menu in
 * {@link Activity#onCreateOptionsMenu(Menu)}.</p>
 * <p/>
 * <p>Note: This is targeted for the native ActionBar/Toolbar, not AppCompat.</p>
 *
 * @param activity the activity to apply the menu tinting on.
 */
public void apply(final Activity activity) {

    if (forceIcons) {
        forceMenuIcons(menu);
    }

    for (int i = 0, size = menu.size(); i < size; i++) {
        MenuItem item = menu.getItem(i);
        colorMenuItem(item, menuItemIconColor, menuItemIconAlpha);
        if (reApplyOnChange) {
            View view = item.getActionView();
            if (view != null) {
                if (item instanceof MenuItemImpl) {
                    ((MenuItemImpl) item)
                            .setSupportOnActionExpandListener(new SupportActionExpandListener(this));
                } else {
                    item.setOnActionExpandListener(new NativeActionExpandListener(this));
                }
            }
        }
    }

    actionBarView = findActionBar(activity);
    if (actionBarView == null) {
        Log.w(LOG_TAG, "Could not find the ActionBar");
        return;
    }

    // We must wait for the view to be created to set a color filter on the drawables.
    actionBarView.post(new Runnable() {

        @Override
        public void run() {
            for (int i = 0, size = menu.size(); i < size; i++) {
                MenuItem menuItem = menu.getItem(i);
                if (isInOverflow(menuItem)) {
                    colorMenuItem(menuItem, subMenuIconColor, subMenuIconAlpha);
                }
                if (menuItem.hasSubMenu()) {
                    SubMenu subMenu = menuItem.getSubMenu();
                    for (int j = 0; j < subMenu.size(); j++) {
                        colorMenuItem(subMenu.getItem(j), subMenuIconColor, subMenuIconAlpha);
                    }
                }
            }
            if (menuItemIconColor != null || menuItemIconAlpha != null) {
                overflowButton = findOverflowMenuButton(activity, actionBarView);
                colorOverflowMenuItem(overflowButton);
            }
        }
    });
}

From source file:jahirfiquitiva.iconshowcase.utilities.color.ToolbarTinter.java

/**
 * <p>Sets a ColorFilter and/or alpha on all the {@link MenuItem}s in the menu, including the
 * OverflowMenuButton.</p>/*from ww  w.  ja  v a  2s  .  co  m*/
 * <p>
 * <p>Call this method after inflating/creating your menu in
 * {@link Activity#onCreateOptionsMenu(Menu)}.</p>
 * <p>
 * <p>Note: This is targeted for the native ActionBar/Toolbar, not AppCompat.</p>
 *
 * @param activity the activity to apply the menu tinting on.
 */
public void apply(final Activity activity) {

    if (menu != null) {
        if (forceIcons) {
            forceMenuIcons(menu);
        }

        for (int i = 0, size = menu.size(); i < size; i++) {
            MenuItem item = menu.getItem(i);
            colorMenuItem(item, iconsColor, iconsAlpha);
            if (reApplyOnChange) {
                View view = item.getActionView();
                if (view != null) {
                    if (item instanceof MenuItemImpl) {
                        ((MenuItemImpl) item)
                                .setSupportOnActionExpandListener(new SupportActionExpandListener(this));
                    } else {
                        item.setOnActionExpandListener(new NativeActionExpandListener(this));
                    }
                }
            }
        }
    }

    actionBarView = findActionBar(activity);
    if (actionBarView == null) {
        Log.w(TAG, "Could not find the ActionBar");
        return;
    }

    // We must wait for the view to be created to set a color filter on the drawables.
    actionBarView.post(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < actionBarView.getChildCount(); i++) {
                final View v = actionBarView.getChildAt(i);

                //Step 1 : Changing the color of back button (or open drawer button).
                if (v instanceof ImageButton) {
                    //Action Bar back button
                    ((ImageButton) v).getDrawable()
                            .setColorFilter(new PorterDuffColorFilter(iconsColor, PorterDuff.Mode.SRC_ATOP));
                }
            }
            if (menu != null) {
                for (int i = 0, size = menu.size(); i < size; i++) {
                    MenuItem menuItem = menu.getItem(i);
                    if (isInOverflow(menuItem)) {
                        colorMenuItem(menuItem, iconsColor, iconsAlpha);
                    }
                    if (menuItem.hasSubMenu()) {
                        SubMenu subMenu = menuItem.getSubMenu();
                        for (int j = 0; j < subMenu.size(); j++) {
                            colorMenuItem(subMenu.getItem(j), iconsColor, iconsAlpha);
                        }
                    }
                }
                if (iconsColor != null) {
                    overflowButton = findOverflowMenuButton(activity, actionBarView);
                    colorOverflowMenuItem(overflowButton);
                }
            }
        }
    });
}

From source file:net.sf.diningout.app.ui.FriendsFragment.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    if (!mListener.onFriendsOptionsMenu()) {
        return;/*from   ww  w  .  ja va  2 s  .c  om*/
    }
    inflater.inflate(R.menu.friends, menu);
    if (mInit) {
        menu.removeItem(R.id.search);
    } else {
        MenuItem item = menu.findItem(R.id.search);
        mSearch = (SearchView) item.getActionView();
        mSearch.setSearchableInfo(Managers.search(a).getSearchableInfo(a.getComponentName()));
        SearchViews.setBackground(mSearch, R.drawable.textfield_searchview);
        mSearch.setOnSearchClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                event("friends", "search");
            }
        });
        mSearch.setOnQueryTextListener(new SearchTextListener());
        item.setOnActionExpandListener(new SearchExpandListener());
    }
    if (!Intents.hasActivity(a, sAddIntent)) {
        menu.removeItem(R.id.add);
    }
}

From source file:net.ustyugov.jtalk.activity.XMLConsole.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.xml, menu);/*from  w  ww. ja  v a  2  s .c o  m*/

    MenuItem.OnActionExpandListener listener = new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            searchString = "";
            updateList();
            return true;
        }

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }
    };

    SearchView searchView = new SearchView(this);
    searchView.setQueryHint(getString(android.R.string.search_go));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            searchString = query;
            updateList();
            return true;
        }
    });

    MenuItem item = menu.findItem(R.id.search);
    item.setActionView(searchView);
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    item.setOnActionExpandListener(listener);
    return super.onCreateOptionsMenu(menu);
}

From source file:com.vishwa.pinit.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_search:
        final MenuItem createNoteItem = mMenu.getItem(1);
        createNoteItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        item.setOnActionExpandListener(new OnActionExpandListener() {

            @Override// w  ww . j a va 2 s. c  om
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                createNoteItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                return true;
            }
        });
        break;
    case R.id.action_create_note:
        mMapEditMode = MapEditMode.CREATE_NOTE;
        hideNoteEditButtons();
        mMenu.findItem(R.id.action_create_note).setVisible(false);
        mMenu.findItem(R.id.action_cancel).setVisible(true).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        Toast.makeText(getApplicationContext(), "Press and hold the location where you'd like to create a note",
                Toast.LENGTH_SHORT).show();
        break;
    case R.id.action_logout:
        if (ParseFacebookUtils.getSession() != null) {
            ParseFacebookUtils.getSession().closeAndClearTokenInformation();
        }
        ParseUser.logOut();
        finish();
        break;
    case R.id.action_refresh:
        if (!PinItUtils.isOnline(getApplicationContext())) {
            PinItUtils.createAlert("Internet connection not found.",
                    "Connect to the Internet and press the refresh button at the top", this);
            mHasInternet = false;
            hideNonRefreshMenuItems();

        } else {
            mHasInternet = true;
            showNonRefreshMenuItems();
            loadMapWhenOnline();

            mMap.getUiSettings().setAllGesturesEnabled(true);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setZoomGesturesEnabled(true);
        }
        break;
    case R.id.action_edit_location:
        if (mFocusedMarker != null) {
            Toast.makeText(getApplicationContext(), "Press and hold the current note and then drag it to where "
                    + "you'd like to position it and click save", Toast.LENGTH_LONG).show();
            mMenu.findItem(R.id.action_save).setVisible(true);
            mMenu.findItem(R.id.action_cancel).setVisible(true);
            mMenu.findItem(R.id.action_create_note).setVisible(false);
            mMenu.findItem(R.id.action_search).setVisible(false);
            mMenu.findItem(R.id.action_edit).setVisible(false);
            for (Marker marker : mMarkerList) {
                marker.setDraggable(false);
            }
            mFocusedMarker.setDraggable(true);
        } else {
            Toast.makeText(getApplicationContext(),
                    "Please click on the note you'd like " + "to move and then try again", Toast.LENGTH_SHORT)
                    .show();
        }
        break;
    case R.id.action_save:
        if (mHasInternet) {
            setProgressBarIndeterminateVisibility(true);
            ParseQuery query = new ParseQuery("Note");
            query.getInBackground(mNoteStore.get(mFocusedMarker.getId()).getNoteId(), new GetCallback() {
                public void done(ParseObject object, ParseException e) {
                    if (e == null) {
                        ParseGeoPoint geopoint = new ParseGeoPoint(mFocusedMarker.getPosition().latitude,
                                mFocusedMarker.getPosition().longitude);
                        object.put("geopoint", geopoint);
                        object.saveInBackground(new SaveCallback() {

                            @Override
                            public void done(ParseException e) {
                                if (e == null) {
                                    setProgressBarIndeterminateVisibility(false);
                                    mFocusedMarker.setDraggable(false);
                                    hideNoteEditButtons();
                                    mMenu.findItem(R.id.action_edit).setVisible(true);
                                    Toast.makeText(getApplicationContext(), "Note location updated!",
                                            Toast.LENGTH_LONG).show();
                                } else {
                                    PinItUtils.createAlert("This note could not be updated.",
                                            "We apologize, this note update failed, please try again",
                                            MainActivity.this);
                                }
                            }
                        });
                    } else {
                        PinItUtils.createAlert("This note could not be updated.",
                                "We apologize, this note update failed, please try again", MainActivity.this);
                    }
                }
            });
        }
        break;
    case R.id.action_delete_note:
        if (mFocusedMarker != null) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("Are you sure?");
            dialog.setMessage("Please confirm that you'd like to delete this note.");
            dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {
                    final Note note = mNoteStore.get(mFocusedMarker.getId());
                    ParseQuery query = new ParseQuery("Note");
                    query.getInBackground(note.getNoteId(), new GetCallback() {

                        @Override
                        public void done(ParseObject object, ParseException e) {
                            if (e == null) {
                                object.deleteInBackground(new DeleteCallback() {

                                    @Override
                                    public void done(ParseException e) {
                                        if (e == null) {
                                            Toast.makeText(getApplicationContext(), "Note deleted!",
                                                    Toast.LENGTH_SHORT).show();
                                            if (mFocusedMarker != null) {
                                                mNoteStore.remove(mFocusedMarker.getId());
                                                mReverseNoteStore.remove(note.getNoteId());
                                                Iterator<Marker> iterator = mMarkerList.iterator();
                                                while (iterator.hasNext()) {
                                                    Marker marker = iterator.next();
                                                    if (marker.getId().equals(mFocusedMarker.getId())) {
                                                        mFocusedMarker.remove();
                                                        mFocusedMarker = null;
                                                        iterator.remove();
                                                        break;
                                                    }
                                                }
                                                hideNoteEditButtons();
                                            }
                                        }
                                    }
                                });
                            } else {
                                PinItUtils.createAlert("Something's gone wrong",
                                        "Please try deleting the note again", MainActivity.this);
                            }
                        }
                    });
                }
            });
            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            dialog.show();
        }
        break;
    case R.id.action_edit_note:
        if (mFocusedMarker != null) {
            Note note = mNoteStore.get(mFocusedMarker.getId());
            Intent intent = new Intent(this, EditNoteActivity.class);
            intent.putExtra("note", note);
            startActivityForResult(intent, REQUEST_CODE_EDIT_NOTE);
        } else {
            Toast.makeText(getApplicationContext(),
                    "Please click on the note you'd like " + "to edit and then try again", Toast.LENGTH_SHORT)
                    .show();
        }
        break;
    case R.id.action_cancel:
        if (mFocusedMarker != null) {
            double latitude = mNoteStore.get(mFocusedMarker.getId()).getNoteLatitude();
            double longitude = mNoteStore.get(mFocusedMarker.getId()).getNoteLongitude();
            LatLng geopoint = new LatLng(latitude, longitude);
            mFocusedMarker.setPosition(geopoint);
            mFocusedMarker.setDraggable(false);
            mFocusedMarker.hideInfoWindow();
        }
        if (mMapEditMode == MapEditMode.CREATE_NOTE) {
            mMapEditMode = MapEditMode.DEFAULT_MODE;
        }
        hideNoteEditButtons();
        break;
    case R.id.action_settings:
        Intent settingsIntent = new Intent(this, SettingsActivity.class);
        startActivityForResult(settingsIntent, REQUEST_CODE_CHANGE_SETTINGS);
        break;
    case R.id.action_about:
        Intent intent = new Intent(this, AboutActivity.class);
        startActivity(intent);
        break;
    default:
        return super.onOptionsItemSelected(item);
    }

    return true;
}

From source file:com.cyanogenmod.eleven.ui.activities.SearchActivity.java

/**
 * {@inheritDoc}//from w  w  w. j a  va  2  s.  c  o  m
 */
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    // if we are not a top level search view, we do not need to create the search fields
    if (!mTopLevelSearch) {
        return super.onCreateOptionsMenu(menu);
    }

    // Search view
    getMenuInflater().inflate(R.menu.search, menu);

    // Filter the list the user is looking it via SearchView
    MenuItem searchItem = menu.findItem(R.id.menu_search);
    mSearchView = (SearchView) searchItem.getActionView();
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setQueryHint(getString(R.string.searchHint).toUpperCase());

    // The SearchView has no way for you to customize or get access to the search icon in a
    // normal fashion, so we need to manually look for the icon and change the
    // layout params to hide it
    mSearchView.setIconifiedByDefault(false);
    mSearchView.setIconified(false);
    int searchButtonId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
    ImageView searchIcon = (ImageView) mSearchView.findViewById(searchButtonId);
    searchIcon.setLayoutParams(new LinearLayout.LayoutParams(0, 0));

    searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            quit();
            return false;
        }
    });

    menu.findItem(R.id.menu_search).expandActionView();

    return super.onCreateOptionsMenu(menu);
}

From source file:cn.edu.wyu.documentviewer.DocumentsActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.activity, menu);

    // Actions are always visible when showing as dialog
    if (mShowAsDialog) {
        for (int i = 0; i < menu.size(); i++) {
            menu.getItem(i).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }//from   ww  w  . j  a v a 2  s.c o  m
    }

    final MenuItem searchMenu = menu.findItem(R.id.menu_search);
    mSearchView = (SearchView) searchMenu.getActionView();
    mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            mState.currentSearch = query;
            mSearchView.clearFocus();
            onCurrentDirectoryChanged(ANIM_NONE);
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

    searchMenu.setOnActionExpandListener(new OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            if (mIgnoreNextCollapse) {
                mIgnoreNextCollapse = false;
                return true;
            }

            mState.currentSearch = null;
            onCurrentDirectoryChanged(ANIM_NONE);
            return true;
        }
    });

    mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {
            if (mIgnoreNextClose) {
                mIgnoreNextClose = false;
                return false;
            }

            mState.currentSearch = null;
            onCurrentDirectoryChanged(ANIM_NONE);
            return false;
        }
    });

    return true;
}

From source file:inc.bait.jubilee.ui.fragments.ContactsListFragment.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override// w  ww  .  j a va  2 s . c o m
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.contact_list_menu, menu);
    MenuItem searchItem = menu.findItem(R.id.menu_search);
    if (isSearchResultView) {
        searchItem.setVisible(false);
    }
    if (ApiHelper.hasHoneycomb()) {
        final SearchManager searchManager = (SearchManager) getActivity()
                .getSystemService(Context.SEARCH_SERVICE);
        final SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String queryText) {
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
                if (searchString == null && newFilter == null) {
                    return true;
                }
                if (searchString != null && searchString.equals(newFilter)) {
                    return true;
                }
                searchString = newFilter;
                mSearchQueryChanged = true;
                getLoaderManager().restartLoader(ContactsQuery.QUERY_ID, null, ContactsListFragment.this);
                return true;
            }
        });

        if (ApiHelper.hasICS()) {
            searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
                @Override
                public boolean onMenuItemActionExpand(MenuItem menuItem) {
                    return true;
                }

                @Override
                public boolean onMenuItemActionCollapse(MenuItem menuItem) {
                    if (!TextUtils.isEmpty(searchString)) {
                        onSelectionCleared();
                    }
                    searchString = null;
                    getLoaderManager().restartLoader(ContactsQuery.QUERY_ID, null, ContactsListFragment.this);
                    return true;
                }
            });
        }

        if (searchString != null) {
            final String savedSearchTerm = searchString;

            // Expands the search menu item
            if (ApiHelper.hasICS()) {
                searchItem.expandActionView();
            }
            searchView.setQuery(savedSearchTerm, false);
        }
    }
}

From source file:dev.dworks.apps.anexplorer.DocumentsActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.activity, menu);

    // Actions are always visible when showing as dialog
    /*        if (mShowAsDialog) {
    for (int i = 0; i < menu.size(); i++) {
        menu.getItem(i).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    }/* w w  w  .j  a v  a2 s  . co  m*/
            }
    */
    final MenuItem searchMenu = menu.findItem(R.id.menu_search);
    mSearchView = (SearchView) searchMenu.getActionView();
    mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            mState.currentSearch = query;
            mSearchView.clearFocus();
            onCurrentDirectoryChanged(ANIM_NONE);
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

    searchMenu.setOnActionExpandListener(new OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            if (mIgnoreNextCollapse) {
                mIgnoreNextCollapse = false;
                return true;
            }

            mState.currentSearch = null;
            onCurrentDirectoryChanged(ANIM_NONE);
            return true;
        }
    });

    mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {
            if (mIgnoreNextClose) {
                mIgnoreNextClose = false;
                return false;
            }

            mState.currentSearch = null;
            onCurrentDirectoryChanged(ANIM_NONE);
            return false;
        }
    });

    return true;
}

From source file:com.jackleeentertainment.oq.ui.layout.fragment.ContactsListFragment.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override/*from   w  ww  .j a  v  a  2 s .c  o m*/
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    // Inflate the menu items
    inflater.inflate(R.menu.contact_list_menu, menu);
    // Locate the search item
    MenuItem searchItem = menu.findItem(R.id.menu_search);

    // In version 3.0 and later, sets up and configures the ActionBar SearchView
    if (Utils.hasHoneycomb()) {

        // Retrieves the system search manager service
        final SearchManager searchManager = (SearchManager) getActivity()
                .getSystemService(Context.SEARCH_SERVICE);

        // Retrieves the SearchView from the search menu item
        final SearchView searchView = (SearchView) searchItem.getActionView();

        // Assign searchable info to SearchView
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));

        // Set listeners for SearchView
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String queryText) {
                // Nothing needs to happen when the user submits the search string
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // Called when the action bar search text has changed.  Updates
                // the search filter, and restarts the loader to do a new query
                // using the new search string.
                String newFilter = !TextUtils.isEmpty(newText) ? newText : null;

                // Don't do anything if the filter is empty
                if (mSearchTerm == null && newFilter == null) {
                    return true;
                }

                // Don't do anything if the new filter is the same as the current filter
                if (mSearchTerm != null && mSearchTerm.equals(newFilter)) {
                    return true;
                }

                // Updates current filter to new filter
                mSearchTerm = newFilter;

                // Restarts the loader. This triggers onCreateLoader(), which builds the
                // necessary content Uri from mSearchTerm.
                mSearchQueryChanged = true;
                getLoaderManager().restartLoader(ContactsQuery.QUERY_ID, null, ContactsListFragment.this);
                return true;
            }
        });

        if (Utils.hasICS()) {
            // This listener added in ICS
            searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
                @Override
                public boolean onMenuItemActionExpand(MenuItem menuItem) {
                    // Nothing to do when the action item is expanded
                    return true;
                }

                @Override
                public boolean onMenuItemActionCollapse(MenuItem menuItem) {
                    // When the user collapses the SearchView the current search string is
                    // cleared and the loader restarted.
                    if (!TextUtils.isEmpty(mSearchTerm)) {
                        onSelectionCleared();
                    }
                    mSearchTerm = null;
                    getLoaderManager().restartLoader(ContactsQuery.QUERY_ID, null, ContactsListFragment.this);
                    return true;
                }
            });
        }

        if (mSearchTerm != null) {
            // If search term is already set here then this fragment is
            // being restored from a saved state and the search menu item
            // needs to be expanded and populated again.

            // Stores the search term (as it will be wiped out by
            // onQueryTextChange() when the menu item is expanded).
            final String savedSearchTerm = mSearchTerm;

            // Expands the search menu item
            if (Utils.hasICS()) {
                searchItem.expandActionView();
            }

            // Sets the SearchView to the previous search string
            searchView.setQuery(savedSearchTerm, false);
        }
    }
}