How can I reuse an Android fragment instance for different fragments?

Here is my use case:

I need to create 3 tabs using the ActionBar navigation tabs , and I use ActionBarSherlock to accomplish this. Each of the three tabs is its own fragment . However, there is general information that is displayed on each tab (in my case, the name of the product, description). I created another fragment for this general information and refer to this fragment in each of the main fragment layouts, for example this .

Here is my problem:

I want to reuse an instance of Fragment that retrieves and displays general information. I use the following code, but it always creates a new instance of the common fragment in each of the main fragments.

    FragmentManager fm = getFragmentManager();
    f = (ProductDetailsInfoFragment) fm.findFragmentByTag("prodinfo");

    if (f == null) {
        Log.d(TAG, "fragment not found...creating new instance");

        f = new ProductDetailsInfoFragment();
        f.setTargetFragment(this, 0);
        fm.beginTransaction().replace(R.id.prod_info_fragment, f, "prodinfo").commit();         
    }
+5
source share
1 answer

You can share fragments if you want. You will need to implement ActionBar.TabListener, and in your onTabSelected just select which fragment you want to use.

You can do something like this: https://gist.github.com/anonymous/5415274

A - , , , . , , . , , , .

+2

All Articles