0

可能重复:
Android 片段 setRetainInstance(true) 不起作用(Android 支持库)

我写了一个简单的测试项目,但我不明白为什么我总是在生命周期方法 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;
}

}

4

1 回答 1

0

我见过同样的问题。但是您可以通过其他方式保存 instate 状态,这要归功于 setRetainInstance(true) 方法,您的所有类数据都会自动保存。

@Override
public void onCreate(Bundle savedInstanceState) {
    setRetainInstance(true);
    super.onCreate(savedInstanceState);
}

编辑

声明活动时也尝试添加这些参数:

    <activity
        android:name="MyActivity"
        android:configChanges="orientation|keyboardHidden|screenSize" />
于 2012-10-15T15:35:09.810 回答