0

I am currently using android sliding menu library from https://github.com/jfeinstein10/SlidingMenu. It's great but I have no idea how to toggle without recreating a new fragment.

I have two fragments called A, B. A menu list : Item A, Item B.

I followed the tutorial and in the onListItemClick I have:

public void onListItemClick(ListView l, View v, int position, long id){
    Fragment newContent = null;
    switch (position) {
      case 0:
        newContent = new FragmentA();
        break;
      case 1:
        newContent = new FragmentB();
        break;
}

As you can see, when I click on ItemA/ItemB, it will create new fragment A/B. How can I avoid this? How can I go to either fragment without recreating new one? Instead, it will direct to the old fragments. Thanks in advance.

Shumin
  • 991
  • 2
  • 13
  • 22
  • you need to understand backstack for that, its better u go through the article and do it by yourself rather then me putting code for you, if you have confusion after this, do comment back I will help http://developer.android.com/training/implementing-navigation/temporal.html – Techfist Sep 15 '14 at 04:35
  • Hi, thanks for quick response. I read that before. I am confused how to go directly to the proper fragments that I first created. For instant, the two fragments were created once I run the app. Then, I toggle the menu and click on "ItemB", which will go to fragment B without recreating it. Also, if I click on "ItemA", it will direct to previous fragment A. Can you explain it clearly? Appreciate! – Shumin Sep 15 '14 at 04:55

1 Answers1

0

Use newInstance pattern used by Android documentation and override default behavior of newInstance method:

private static MyFragment instance;

public static MyFragment getInstance(String p1, String p2) {
    if( instance == null ) {
        MyFragment fragment = new MyFragment();
    }
    Bundle args = new Bundle();
    args.putString(ARG_1, p1);
    args.putString(ARG_2, p2);
    fragment.setArguments(args);
    return fragment;
}

and then each time you need to display this fragment, just call MyFragment.getInstance("","").

Ali Behzadian Nejad
  • 8,804
  • 8
  • 56
  • 106