我写了一个虚拟活动,可以在两个片段之间切换。当您从FragmentA转到FragmentB时,FragmentA被添加到后台堆栈中。但是,当我返回FragmentA(按回去)时,会创建一个全新的FragmentA,并且它所处的状态会丢失。我感觉自己对这个问题也很满意,但是我提供了完整的代码示例来帮助解决问题:
public class FooActivity extends Activity {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new FragmentA());
transaction.commit();
}
public void nextFragment() {
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new FragmentB());
transaction.addToBackStack(null);
transaction.commit();
}
public static class FragmentA extends Fragment {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View main = inflater.inflate(R.layout.main, container, false);
main.findViewById(R.id.next_fragment_button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((FooActivity) getActivity()).nextFragment();
}
});
return main;
}
@Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save some state!
}
}
public static class FragmentB extends Fragment {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.b, container, false);
}
}
}
加上一些日志消息:
07-05 14:28:59.722 D/OMG ( 1260): FooActivity.onCreate
07-05 14:28:59.742 D/OMG ( 1260): FragmentA.onCreateView
07-05 14:28:59.742 D/OMG ( 1260): FooActivity.onResume
<Tap Button on FragmentA>
07-05 14:29:12.842 D/OMG ( 1260): FooActivity.nextFragment
07-05 14:29:12.852 D/OMG ( 1260): FragmentB.onCreateView
<Tap 'Back'>
07-05 14:29:16.792 D/OMG ( 1260): FragmentA.onCreateView
它从不调用FragmentA.onSaveInstanceState,并且在您回击时会创建一个新的FragmentA。但是,如果我在FragmentA上并且锁定了屏幕,则会调用FragmentA.onSaveInstanceState。所以很奇怪...我期望添加到后端堆栈的片段不需要重新创建是我错了吗?这是文档所说的:
而如果您在删除片段时确实调用了addToBackStack(),则该片段将停止并在用户向后导航时恢复。
ListView
。似乎过多的跳跳无法附加滚动侦听器和更新实例变量。