Search code examples
androidandroid-fragmentsandroid-actionbaractionbarsherlockactionview

expanding an actionBar-ActionView in combination with showing a new Fragment


Several tries to ask this question in #android-dev (irc) and hours of searching, but I still don't have a solution to this problem.

I'm currently working on the search-function in my android music player. I'm using the amazing ActionBarSherlock to provide support for older android versions.

My Problem is the following: When the user clicks the search menu/action button, the actionView of the clicked action should be expanded, and a new Fragment (the searchFragment) should be shown instead of the currently active one. However when i'm attempting to do this, the actionView doesn't expand.

I've tried to expand the actionView, without adding the SearchFragment, and in that case the actionView DOES expand. However the combination seems impossible.

Here's my code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item != null) {
        if (item.getItemId() == R.id.collectionactivity_search_menu_button) {
            item.expandActionView();
            mTabsAdapter.replace(new SearchFragment(), false);
            return true;
        }
    }
    return false;
}

/**
 * Replaces the view pager fragment at specified position.
 */
public void replace(int position, Fragment newFragment, boolean isBackAction) {
    // Get currently active fragment.
    ArrayList<Fragment> fragmentsStack = mFragments.get(position);
    Fragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1);
    if (currentFragment == null) {
        return;
    }
    // Replace the fragment using a transaction.
    this.startUpdate(mViewPager);
    FragmentTransaction ft = mFragmentManager.beginTransaction();
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.attach(newFragment).remove(currentFragment).commit();
    if (isBackAction == true)
        fragmentsStack.remove(currentFragment);
    else
        fragmentsStack.add(newFragment);
    this.notifyDataSetChanged();
    this.finishUpdate(mViewPager);
}

The mTabsAdapter.replace(...) method replaces the currently shown Fragment with the one in the first parameter. In Addition the fragment is being added to a custom backStack. Replacing the Fragment before or after expanding the View didn't make any difference.

Hopefully somebody is able to help me :) thanks in advance!


Solution

  • I found out what the problem was caused by.

    My mTabsAdapter.replace(..) method was calling notifyDataSetChanged();. So everytime I replaced the fragment, onPrepareOptionsMenu was being called, resulting in the search action button being removed and added again, thus resulting in the actionView being collapsed.

    The solution to this is to fix my onPrepareOptionsMenu, so the actionView will be expanded again, whenever onPrepareOptionsMenu is called and the actionView was expanded before.