2016-06-01 38 views
0

空值,這是我在一類onCreate方法是片段savedInstanceState總是在的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總是空並打印進來。

+0

活動時已凍結狀態,即主要是在配置變化(旋轉等)保存的狀態只恢復了。沒有保存的狀態,當你從頭開始重新創建活動。你是否期望保存的狀態比現在更持久? – dhke

+0

當我旋轉屏幕時,我想獲得計數器變量。 –

回答

1

重寫protected void onRestoreInstanceState(Bundle savedInstanceState)並查看是否可以在那裏獲取您的值。

+0

onRestoreInstanceState方法在超類中不存在。我正在擴展片段類。 –

+0

從父Activity中獲取它oRestoreInstanceState()並通過某種方法將它傳遞給可見片段。 –

0

嘗試將您的值保存在您的分段宿主活動中(您的分段定義的活動)。從主機活動中,您必須提取該值並在片段子類中訪問它。

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 
} 
相關問題