【问题标题】:How can I maintain a child view's state when switching fragments?切换片段时如何维护子视图的状态?
【发布时间】:2014-09-01 03:42:50
【问题描述】:

我很难理解片段生命周期与在后台堆栈中的片段之间切换的关系。如果我的问题暴露了多个误解,请多多包涵。

这是我的代码:

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,并且没有片段。现在我必须添加功能,所以我将自定义视图变成了一个片段,因此我遇到了这个问题。

【问题讨论】:

    标签: android android-fragments back-stack


    【解决方案1】:

    我找到了一个适合我的答案。 FragmentTransaction 类有许多方法可以让你切换片段的输入/输出。 (FragmentTransaction 的 Android 文档是 heregreat 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() 或者如果您在添加/附加其他片段时使用addToBackStack(),Android 会在用户单击“返回”时自动执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多