片段setRetainInstance不起作用(Android支持lib)

时间:2012-10-15 15:27:52

标签: android android-fragments android-support-library

  

可能重复:
  Android fragments setRetainInstance(true) not works (Android support library)

我编写了一个简单的测试项目,但我无法理解为什么我总是在生命周期方法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扩展了Fragment {

@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;
}

}

1 个答案:

答案 0 :(得分:0)

我见过同样的问题。但是你可以用另一种方式保存instate状态,多亏了方法setRetainInstance(true),你的所有类数据都会自动保存。

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

修改

在宣布您的活动时,请尝试添加这些参数:

    <activity
        android:name="MyActivity"
        android:configChanges="orientation|keyboardHidden|screenSize" />