savedCstate

时间:2016-06-01 06:45:25

标签: android

这是我在类中的onCreate方法,它是片段

的子类
static  int counter = 0;
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    if(savedInstanceState == null) { //made for first time
        Log.d("came in", "Came in");
        counter = 0;
    } else {
        counter = savedInstanceState.getInt("counter", 0);
    }
}

这是我的savedInstanceState方法

@Override
public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    Log.d("hi there", ""+counter); // this is printing hi there 3
    outState.putInt("counter", counter);//key value pair
}

但在onCreate方法中,savedInstanceState始终为null并且打印进来。

3 个答案:

答案 0 :(得分:1)

覆盖protected void onRestoreInstanceState(Bundle savedInstanceState),看看你是否可以在那里获得你的价值。

答案 1 :(得分:0)

尝试将您的值保存在片段主机活动中(定义片段的活动)。从主机活动中,您必须提取该值并在您的片段子类中访问它。

答案 2 :(得分:0)

尝试将onSaveInstanceState方法更改为:

@Override
public void onSaveInstanceState(Bundle outState){    
    Log.d("hi there", ""+counter); // this is printing hi there 3
    outState.putInt("counter", counter);//key value pair
    super.onSaveInstanceState(outState); // call super after put int
}
相关问题