Android 如何维护子视图';切换片段时的状态是什么?
我很难理解片段生命周期与在后堆栈中的片段之间切换的关系。如果我的问题暴露出不止一种误解,请原谅我 这是我的密码:Android 如何维护子视图';切换片段时的状态是什么?,android,android-fragments,back-stack,Android,Android Fragments,Back Stack,我很难理解片段生命周期与在后堆栈中的片段之间切换的关系。如果我的问题暴露出不止一种误解,请原谅我 这是我的密码: public class SomeFragment extends Fragment { private SomeCustomView customView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanc
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
,因此我释放了avariablewhichmustpersistedforlifeTimeofApplication
。这给我带来了各种各样的问题
应用程序使用一个只显示
SomeCustomView
的活动启动,没有片段。现在我必须添加功能,因此我将自定义视图变成了一个片段,从而解决了这个问题。我找到了一个适合我的答案。FragmentTransaction
类有许多方法,允许您将片段切换入/出。(关于FragmentTransaction
的Android文档是,关于堆栈溢出的解释是。)
在我的例子中,我希望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\u fragment\u占位符
。请注意,我使用的是hide()
而不是replace()
,这是防止视图被破坏的关键区别。当您想要取回片段时,您可以使用show()
,或者如果在添加/附加其他片段时使用addToBackStack()
,当用户单击“返回”时,Android将自动执行此操作