如何在配置更改期间将Fragment保留在以编程方式添加的ViewGroup中

时间:2015-03-15 23:49:54

标签: android android-fragments

让我们说

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消失,特别是第一个(从第二个恢复它们)。

0 个答案:

没有答案