[英]savedInstanceState is always null value in onCreate
這是我的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);
}
}
這是我的saveInstanceState方法
@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,並且可以打印。
覆蓋protected void onRestoreInstanceState(Bundle savedInstanceState)
並查看是否可以在那里獲取值。
嘗試將您的值保存在片段主機活動(定義片段的活動)中。 從主機活動中,您必須提取該值並在片段子類中訪問它。
嘗試將您的方法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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.