Fragment中的onSaveInstanceState不起作用?

时间:2016-04-11 19:51:50

标签: android screen-rotation savestate

我需要帮助。我不知道这里有什么问题。需要保存的实例数据片段,但它对我不起作用?有人可以帮忙吗?这是我的代码:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        if (savedInstanceState == null) {
            Log.e(getActivity().getClass().getSimpleName(),"DATA is NULL");
        }else{
            Log.e(getActivity().getClass().getSimpleName(),"DATA IS NOT NULL " + savedInstanceState.getString(Constans.SAMPLEDATA));
        }


@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(Constans.MOVIE, movie);
        outState.putString(Constans.SAMPLEDATA, "sampleData");
    }

2 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为在屏幕旋转时,您的活动会被重新创建,因此它内部的片段从初始位置开始,因为它是在活动首次启动时启动的

您需要在活动的onCreate中添加此内容,并在if语句中设置片段,如此示例

if (savedInstanceState == null){

        launchfragment

    } else {

        // do nothing
    }

希望这会有所帮助

答案 1 :(得分:0)

添加 super.onSaveInstanceState(outState);

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putParcelable(Constans.MOVIE, movie);
    outState.putString(Constans.SAMPLEDATA, "sampleData");
    super.onSaveInstanceState(outState);
}