0

I am developing android application with one activity and multiple fragments. My app contains navigation drawer. It's layout contains listview. Clicking it's items I change fragments dynamically with ft.replace(R.id.my_placehodler, new MyFragment()) and adding transactions to backstack ft.addToBackstack(null). when I make new transaction every time I instantiate new fragment. It seems to me its not a good approach. Can you give me suggestions about the right way of making fragment transactions?

Remees M Syde
  • 2,564
  • 1
  • 19
  • 42
user3816018
  • 55
  • 1
  • 8

2 Answers2

0

Just call a setFragment(FragmentClassObject,false,"fragment"); method.

public void setFragment(Fragment fragment, boolean backStack, String tag) {
    manager = getSupportFragmentManager();
    fragmentTransaction = manager.beginTransaction();
    if (backStack) {
        fragmentTransaction.addToBackStack(tag);
    }
    fragmentTransaction.replace(R.id.content_frame, fragment, tag);
    fragmentTransaction.commit();
}
Jaydeep
  • 110
  • 8
0

If you would avoid instanciating multiple instances for the same class of Fragment, that is you want to have single instance per a class of Fragment, you can recognize each Fragments by using tags.

@Override
public void onNavigationDrawerItemSelected(int position) {
    String tag = "";
    switch (position) {
    case 0:
        tag = "fragment_0";
        break;
    case 1:
        tag = "fragment_1";
        break;
    case 2:
        tag = "fragment_2";
        break;
    }

    FragmentManager fragmentManager = getFragmentManager();
    Fragment fragment = fragmentManager.findFragmentByTag(tag);
    if (fragment == null) {
        // Only in case there is no already instaciated one,
        // a new instance will be instanciated.
        switch (position) {
        case 0:
            fragment = new Fragment_class_0();
            break;
        case 1:
            fragment = new Fragment_class_1();
            break;
        case 2:
            fragment = new Fragment_class_2();
            break;
        }
    }

    fragmentManager.beginTransaction().replace(R.id.container, fragment, tag).commit();
}
hata
  • 11,633
  • 6
  • 46
  • 69
  • as I got from your reply I have to just set tag to the fragment to get it from fragment manager if its already instantiated. am I right? – user3816018 Dec 03 '14 at 14:10
  • Not just settting. First, setting a tag for the same class (ex. "fragment_0" for Fragment_Class_1, "fragment_1" for Fragment_Class_2, and so on). Second, finding an already instanciated fragment object if exists (findFragmentByTag). If there is no already instanciated object, a new object of the class will be instanciated. – hata Dec 03 '14 at 14:41