ActionBar (ToolBar) - Backpress should be consumed by SearchView and ActionMode

420 views Asked by At

Is there a good way to handle this? Or do I really manually have to keep track of opened search views and active action mode?

At the moment, I implemented it like following in my base activity... But this always needs some short code blocks to register an active action mode or an visible search view... It works perfectly, but I think, there may be a better solution...

Is there a better way?

Btw., I'm using AppCompat... Before, these all didn't need special treatment...

public abstract class BaseActivity
{
    // ----------------
    // manually register opened search view
    // or active action mode
    // ----------------

    public void registerActiveActionMode(ActionMode mode)
    {
        mActiveActionMode = mode;
    }

    public void registerCollapsableMenuItem(MenuItem menuItem)
    {
        mCollapsableMenuItem = menuItem;
    }

    // ------------------
    // delegate backpress...
    // ------------------

    protected boolean checkBackPressConsumed()
    {
        if (closeDrawer())
            return true;

        if (closeActionMode())
            return true;

        if (closeCollapsableMenuItem())
            return true;

        return false;
    }

    // ------------------------
    // back press handler with delegation, if necessary...
    // ------------------------

    @Override
    public void onBackPressed()
    {
        if (checkBackPressConsumed())
            return;

        super.onBackPressed();
    }

    // -------------------------
    // helper functions
    // -------------------------    

    public boolean closeDrawer()
    {
        if (mNavigationDrawerFragment != null)
        {
            if (isDrawerOpen())
            {
                mNavigationDrawerFragment.closeDrawer();
                return true;
            }
        }
        return false;
    }

    public boolean closeActionMode()
    {
        if (mActiveActionMode != null)
        {
            mActiveActionMode.finish();
            mActiveActionMode = null;
            return true;
        }
        return false;
    }

    public boolean closeCollapsableMenuItem()
    {
        if (mCollapsableMenuItem != null)
        {
            MenuItemCompat.collapseActionView(mCollapsableMenuItem);
            mCollapsableMenuItem = null;
            return true;
        }
        return false;
    }
}
1

There are 1 answers

0
Matti Torvaldsson On

I use the AppCompat Toolbar and my SearchView is consuming my backpresses.

As Android Developer Blog says;

"All of your Activities must extend from ActionBarActivity"

link: http://android-developers.blogspot.se/2014/10/appcompat-v21-material-design-for-pre.html

As I see it your BaseActivity is not extending ActionBarActivity, maybe that will solve the problem for ya.