切换片段时如何保持子视图的状态?

时间:2014-07-10 16:43:38

标签: android android-fragments back-stack

我很难理解片段生命周期如何与后端堆栈中的片段之间的切换相关。如果我的问题暴露出多个误解,请耐心等待。

这是我的代码:

public class SomeFragment extends Fragment {
    private SomeCustomView customView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.some_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Create the child view
        customView = (SomeCustomView) getView().findViewById(R.id.some_fragment_child_view);
        customView.initializeMyCustomView();
    }
}

如您所见,我的片段有一个子视图。子视图是自定义视图。这是代码:

public class SomeCustomView extends SurfaceView implements SurfaceHolder.Callback {

    private boolean aVariableWhichMustPersistForLifetimeOfApplication;

}

每当将此片段添加到后台堆栈然后再恢复时,都会重新创建变量customView,因此我会松开aVariableWhichMustPersistForLifetimeOfApplication的值。这给我带来了各种各样的问题。

应用程序使用仅显示Activity且没有片段的SomeCustomView开始。现在我必须添加功能,因此我将自定义视图转换为片段,因此我遇到了这个问题。

2 个答案:

答案 0 :(得分:1)

本文可能对您有所帮助:http://alexfu.github.io/blog/2013/12/09/managing-fragment-states-manually/

此外,您还可以使用SharedPreferences来存储布尔值。

答案 1 :(得分:1)

我找到了一个适合我的答案。 FragmentTransaction类有许多方法允许您切换进/出的片段。 (FragmentTransaction的Android文档为here精彩 StackOverflow解释为here。)

就我而言,我希望SomeFragment永远不会丢失其视图中包含的数据。为此,请使用以下代码:

SomeFragment fragment = new SomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.activity_fragment_placeholder, fragment, "some_fragment");
transaction.commit();

然后再说:

getFragmentManager().beginTransaction().hide(fragment).commit();

您现在可以向R.id.activity_fragment_placeholder添加/附加不同的片段。请注意,我使用hide()而不是replace(),这是阻止视图被销毁的关键区别。当你想要片段回来时,你可以使用show()或者Android会在用户点击" Back"时自动执行此操作。如果您在添加/附加其他片段时使用addToBackStack()