detecting a click on action bar back button -(OnOptionsItemSelected not calling when click on action bar back button)
Asked Answered
F

5

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);
}
Fasano answered 15/10, 2014 at 7:5 Comment(2)
#14438245Ringster
Possible duplicate of how to override action bar back button in android?Bracketing
K
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;
    }
});
Kerplunk answered 20/4, 2015 at 16:43 Comment(2)
This is now deprecatedHyacinthia
try this MenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @ Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @ Override public boolean onMenuItemActionCollapse(MenuItem item) { return true; } }); developer.android.com/reference/android/view/…Fortress
F
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);
}
Fisticuffs answered 15/10, 2014 at 9:54 Comment(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 openFasano
S
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;
    }
Stevenson answered 15/10, 2014 at 7:47 Comment(4)
I has override it but it is not firing when I click on the back buttonFasano
Add below line actionBar.setHomeButtonEnabled(true);Stevenson
Also, Add actionBar.setDisplayHomeAsUpEnabled(true);Stevenson
It is enabled because when I click on back button it is working and close the search view but the onOptionsItemSelected is not firing. Any way, I set this line in the onCreate() method and still it is not firing.Fasano
I
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;
}
Ironic answered 6/4, 2015 at 20:40 Comment(0)
B
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
            }
        });
Bracketing answered 29/8, 2019 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.