让我们说
1)我有这段代码为特定的用户互动添加了新的Fragment
:
ViewGroup vg = (ViewGroup) findViewById(R.id.packetFragmentContainer);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setId(View.generateViewId());
vg.addView(linearLayout);
String fragmentTag = "FRAGMENT_" + linearLayout.getId();
PacketEditorFragment fragment =
(PacketEditorFragment)
getSupportFragmentManager().findFragmentByTag(fragmentTag);
if(fragment == null) {
Log.d(TAG, "No fragment for tag '" + fragmentTag + "'- creating a new fragment");
fragment = PacketEditorFragment.newInstance();
fragment.setRetainInstance(true);
getSupportFragmentManager().beginTransaction()
.add(linearLayout.getId(), fragment, fragmentTag)
.commit();
} else {
Log.d(TAG, "Fragment already in this world");
}
当用户旋转设备时,如何恢复包含Fragments
(以及片段视图)的ViewGroup?
目前,我在LinearLayout
期间保存了fragmentTag
我创建的ID(以及所有onSaveInstanceState
)的ID,并在{{1}期间创建了相同的LinearLayout
元素}或onCreate
州。
然而,每次我旋转设备时,一个onRestoreInstance
消失,特别是第一个(从第二个恢复它们)。