Here is my use case:
I need to create 3 tabs using ActionBar Navigation Tabs, and I am using ActionBarSherlock to accomplish this. Each of the 3 tabs is it's own Fragment. However, there is some common information that is shown in each of the tabs (in my case, product title, description). I have created another Fragment for this common information, and am referencing this Fragment in each of the main Fragment layouts, like this.
Here is my problem:
I want to reuse the Fragment instance that retrieves and displays the common info. I am using the code below, but it always seems to create 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();
}
You can share fragments if you want to. You will need to implement ActionBar.TabListener and in your onTabSelected just pick what fragment you want to use.
You could do something like this: https://gist.github.com/anonymous/5415274
A better option is to store the data that is needed by both of these fragments in a separate object that you can share between them. This will allow you to test the retrieval without having a UI attached to it if you wish. This also allows the two fragments to diverge as they need to, making them a single purpose thing vs. having to keep all the code needed for both actions in a single fragment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With