ZWis212 ZWis212 - 6 months ago 19
Android Question

Navigation Drawer Fragments

So I have my navigation drawer with 5 different options. They all open a new fragment that I have created. The first one is Home, and I am trying to find a way to bring it back to the first screen that shows up under the navigation drawer. It has the id of "container", in the main_activity.xml. I do not want to use and intent to call the entire class again to load up. Also I do not want to be able to use the back button from another intent. I am confused on how to make this happen.

@Override
public void onNavigationDrawerItemSelected(int position) {

FragmentHowItWorks fragmentHow;
FragmentSettings fragmentSettings;
FragmentTransaction transaction = getFragmentManager().beginTransaction();

switch(position){
case 0:

// should I call the layout?
// this is the "Home" option

break;
case 1:
fragmentHow = new FragmentHowItWorks();
transaction.replace(R.id.container, fragmentHow);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
fragmentSettings = new FragmentSettings();
transaction.replace(R.id.container, fragmentSettings);
transaction.addToBackStack(null);
transaction.commit();
break
case 3:
fragment = new FragmentHowItWorks();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 4:
fragment = new FragmentHowItWorks();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
break;
}
}

Answer

Use methods add,hide and show,

Step1 Prepare all your fragments

Fragment fragment1 = new FragmentOne();
Fragment fragment2 = new FragmentTwo();
Fragment fragment3 = new FragmentThree();
Fragment mCurrentFragment = null;

Step2 Show/hide your fragments

@Override
public void onNavigationDrawerItemSelected(int position) {
    Fragment fragment;
    switch (position) {
    case 1:
        fragment = fragment1;
        break;
    case 2:
        fragment = fragment2;
        break;
    case 3:
        fragment = fragment3;
        break;
    }
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    if(mCurrentFragment == null) {
        ft.add(R.id.container, fragment).commit();
        mCurrentFragment = fragment;
    } else if(fragment.isAdded()) {
        ft.hide(mCurrentFragment).show(fragment).commit();
    } else {
        ft.hide(mCurrentFragment).add(R.id.container, fragment).commit();
    }
    mCurrentFragment = fragment;
}
Comments