If I’ve understood correctly the issue here isn’t related to specifically to our ChartFragment but actually to the way you are trying to use Fragments.
It sounds like you’re trying to nest a Fragment within a Fragment by specifying it in the XML. As the Android developer docs state “you cannot inflate a layout into a fragment when that layout includes a <fragment>. Nested fragments are only supported when added to a fragment dynamically”. See http://developer.android.com/about/versions/android-4.2.html#NestedFragments.
Essenatially, the issue is that when the first page-level Fragement is created, the Fragment inside is also created with the id specified in XML. However, when the second page-level Fragment is created, as it’s using the same XML layout file, it attempts to create another (inner) Fragment with the same id as the first inner Fragment. And that first Fragment is still around as the Activity has not been destroyed.
Please note that nested fragments were only introduced in Android 4.2 (though there is provision in the support library to provide backwards compatibility) and that currently our ChartFragment does not support being nested inside another Fragment.
So, back to your question: how do you have swappable charts? There are a couple of options open to you:
- Use a ChartView instead of a ChartFragment in your XML layout.
You’d have to ensure you forward on the lifecycle calls from the Fragment to the ChartView (e.g. override onPause() in you fragment to call super.onPause() and then chartView.onPause()) - see http://www.shinobicontrols.com/docs/ShinobiControls/ShinobiChartsAndroid/1.4.1/Premium/Normal/apidocs/docs/reference/com/shinobicontrols/charts/ChartView.html
The Fragment, and thus the ChartView, won’t be retained over configuration changes so you’ll need to handle this - essentially you’re creating a new ChartView every config change so it just really depends on how you’re setting up your chart and pushing data into it.
- Subclass ChartFragment and override the onCreate() method to setup your chart. Then just instantiate this class rather than the page-level Fragments.
If your page-level Fragments contained additional views around the ChartFragment then this approach probably won’t be as suitable but if not then it could be quite neat.
I hope that helps,