14

I have an action bar containing a searchview. When user click on the search button and collapse the search view the action bar shows a back button on the left side.

enter image description here

How can we detect when user click on this back button?

Edit

based on the answer I checked my OnOptionsItemSelected but it is not calling too. This is the code of my OnOptionsItemSelected:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (item != null && id == android.R.id.home) {
        if (mNavigationDrawerFragment.isDrawerOpen(Gravity.RIGHT)) {
            mNavigationDrawerFragment.closeDrawer(Gravity.RIGHT);
        } else {
            mNavigationDrawerFragment.openDrawer(Gravity.RIGHT);

        }
        return true;
    }
    if (id == R.id.action_search) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Husein Behboudi Rad
  • 5,434
  • 11
  • 57
  • 115
  • http://stackoverflow.com/questions/14437745/how-to-override-action-bar-back-button-in-android – codePG Oct 15 '14 at 07:07
  • Possible duplicate of [how to override action bar back button in android?](https://stackoverflow.com/questions/14437745/how-to-override-action-bar-back-button-in-android) – Zubair Younas Aug 29 '19 at 07:02

5 Answers5

12

Put this on onCreateOptionsMenu method:

MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.action_search), new MenuItemCompat.OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {

        return true;
    }

    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {

        //DO SOMETHING WHEN THE SEARCHVIEW IS CLOSING

        return true;
    }
});
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Lisandro Lopez
  • 144
  • 1
  • 7
  • 1
    This is now deprecated – iBEK Nov 15 '17 at 01:05
  • try this MenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @ Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @ Override public boolean onMenuItemActionCollapse(MenuItem item) { return true; } }); https://developer.android.com/reference/android/view/MenuItem.OnActionExpandListener.html – anoo_radha Feb 05 '18 at 15:51
5

You should add meta data your manifest.xml for which activity you want it

Like

<activity
        android:name=".Example"
        android:label="@string/Example"
        android:theme="Theme.AppCompat.Light">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />
    </activity>

and your code should be like this in Example

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 .......
         getActionBar().setDisplayHomeAsUpEnabled(true);

......
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}
massaimara98
  • 7,401
  • 1
  • 18
  • 18
  • 1
    please see the attached image. I want to detect the press of back button when the search view is showing.I think the code you attached, is working when new activity is opening, not for when search view is open – Husein Behboudi Rad Oct 19 '14 at 07:48
1

Just override below method.

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
             //do whatever you want to do here.

            }
            return true;
    }
Avtar Guleria
  • 2,126
  • 3
  • 21
  • 33
0

Try this: rather than use the onOptionsItemSelected to detect the search change, use an OnQueryTextListener. The onQueryTextChanged will then get called with the back button (and any other time the query text changes).

When you set up your menu, assign the searchView the listener. The onQueryTextChange will get called whenever the search criteria changes (on any keyboard press except the search button), and it will get called with a blank string when the back button is pressed. The onQueryTextSubmit will get called when the search button is pressed on the keyboard.

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);

    final SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            Log.i(TAG,"onQueryTextSubmit: " + s);
            searchView.clearFocus();
            return true;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            Log.i(TAG,"onQueryTextChange: " + s);
            FragmentManager fragmentManager = getSupportFragmentManager();
            Fragment fragment = fragmentManager.findFragmentByTag(currentFragmentTag);
            if (fragment.getClass().getName().startsWith("com.mydomain.myapp.mainactivity.MyFragment")) {
                if (s.isEmpty()) {
                    ((SingleICPListFragment)fragment).clearSearchCriteria();
                } else {
                    ((SingleICPListFragment) fragment).applySearchCriteria(s);
                }
            }
            return true;
        }
    });

    SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    return true;
}
Eric Rowe
  • 53
  • 1
  • 5
0

Possible duplicate of how to override action bar back button in android?

Anyways:

Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Do what you want to do
            }
        });
Zubair Younas
  • 71
  • 1
  • 13