我写了一个简单的测试项目,但我不明白为什么我总是在生命周期方法 onCreate、onCreateView 和 onActivityCreated 中收到 savedInstanceState = null。我更改了屏幕方向,查看日志,但未保存状态。请告诉我我的错误在哪里。谢谢。片段类的代码是:
public class TestFragment extends Fragment {
private String state = "1";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
//never works
state = savedInstanceState.getString("state");
}
//always prints 1
Toast.makeText(getActivity(), state, Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_layout, container, false);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("state", "2");
Log.e("", "saved 2");
}
}
编辑
当我尝试使用 setRetainInstance 时,我再次没有结果(((我使用 btn1 将状态更改为 2,但在更改方向后,按下 btn2 时我看到 1。请帮助(
公共类 TestFragment 扩展片段 {
@Override
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
private String state = "1";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
//button for changing state
((Button)view.findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
state = "2";
}
});
//button for showing state
((Button)view.findViewById(R.id.button2)).setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getActivity(), state, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}