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.
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("","").