Switch between tab navigation and list navigation

I use ActionBarSherlock and use this template to navigate the tab that I found on the Android developer site. It works very well, but I also want to switch between NAVIGATION_MODE_TABSand NAVIGATION_MODE_LISTwhile maintaining the connection between tabs and fragments.

The template mentioned above is pretty good for maintaining common code. Therefore, I add listeners to my tabs and associate them with snippets such as this:

bar.addTab(bar.newTab()
.setText("MyFragment")
.setTabListener(new TabListener<SomeFragment>(this, "myfargment", SomeFragment.class)));

and create an instance of the fragment by clicking on the corresponding tab using generics:

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    if (mFragment == null) {
        mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
        ft.add(android.R.id.content, mFragment, mTag);
    } else {
        ft.attach(mFragment);
    }
}

, , . , OnNavigationListener ActionBar , .

- :

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    switch (itemPosition) {
    case 0:
    //Replace the current fragment with FragmentA
        break;
    case 1:
    //Replace the current fragment with FragmentB
        break;
    case 2:
    //Replace the current fragment with FragmentC
        break;
    default:
        break;
    }
    return true;
}

EDIT:

: NAVIGATION_MODE_TABS, , (, ), , ?

+3
1

, , , . , "" . :

OnNavigationListener mNavigationListener = new OnNavigationListener()
{
int mLastPosition = -1;

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId)
{
    String selectedTag = mFragmentNames.get(itemPosition);

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentByTag(selectedTag);
    FragmentTransaction ft = fm.beginTransaction();

    /** Used to avoid the same fragment being reattached. */
    if(mLastPosition != itemPosition)
    {
    /** Means there was a previous fragment attached. */
    if(mLastPosition != -1)
    {
        Fragment lastFragment = fm.findFragmentByTag(mFragmentNames.get(mLastPosition));
        if(lastFragment != null)
        ft.remove(lastFragment);
    }

    if(fragment == null)
    {
        /** The fragment is being added for the first time. */
        fragment = Fragment.instantiate(HomeActivity.this, selectedTag);
        ft.add(R.id.rootLayout, fragment, selectedTag);
        ft.commit();
    } else
    {
        ft.attach(fragment);
        ft.commit();
    }
    }
    /**
     * The newly attached fragment will be the last position if changed.
     */
    mLastPosition = itemPosition;

    return true;
}
};

mFragmentNames - HashMap, ex. "Com.android.myproject.MyFragment"

, .

+1

All Articles