As reported by the Android guide, dual-pane can be achieved in two ways:
- Multiple fragments, one activity
- Multiple fragments, multiple activities
I am using the first case (the Android guide only explains the second case).
This is what happens on 7" tablets:
- rotating from landscape to portrait: only the single-pane fragment gets recreated
- rotating from portrait to landscape: all 3 fragments (single-pane, dual-pane-master, dual-pane-detail) get recreated
Question: why is the single-pane fragment (which I create programmatically, but using a FrameLayout defined in the layout as the container) get recreated on dual pane?
I am reporting below my implementation:
/layout/activity_main.xml:
<FrameLayout
android:id="@+id/single_pane"
android:layout_width="match_parent"
android:layout_height="match_parent" />
/layout-w900dp/activity_main.xml:
<LinearLayout
android:id="@+id/dual_pane"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment class="com.example.MasterFragment"
android:id="@+id/master_dual"
android:tag="MASTER_FRAGMENT_DUAL_PANE"
android:layout_width="@dimen/master_frag_width"
android:layout_height="match_parent"/>
<fragment class="com.example.DetailFragment"
android:id="@+id/detail_dual"
android:tag="DETAIL_FRAGMENT_DUAL_PANE"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is the onCreate
in the main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDualPane = findViewById(R.id.dual_pane)!=null;
FragmentManager fm = getFragmentManager();
if (savedInstanceState==null) {
// this is a non-UI fragment I am using for data processing purposes
fm.beginTransaction().add(new NonUiFragment(), DATA_FRAGMENT).commit();
}
if (!mDualPane && fm.findFragmentById(R.id.single_pane)==null) {
fm.beginTransaction().add(R.id.single_pane, new MasterFragment(), MASTER_FRAGMENT_SINGLE_PANE).commit();
}
}