我試圖用一個片段的onSaveInstanceState()來保存一個變量的狀態。我試圖保存的變量是在我的程序的另一個類中創建的,但它總是被讀爲0(初始值)。我知道我正在增加變量值。 如何獲得變量的實際值?這是我的代碼:從另一個類獲得變量值的片段
public class ObjectivesActivity extends Fragment {
//Variables
ObjectivesLogic objectivesLogic = new ObjectivesLogic();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
System.out.println("savedInstanceState: " + savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_objectives, container, false);
}
@Override
public void onStart() {
super.onStart();
if (objectivesLogic.getCount()>0){
objectivesLogic.restoreFragment();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
int save = objectivesLogic.getCount();
System.out.println("save: "+save);
outState.putInt("Count",save);
}
}
而這正是我創建變量:
public class ObjectivesLogic extends AppCompatActivity {
//Variables
int count = 0;
View savedLinearLayoutView = null;
Context savedContext = null;
public void addObjective(Context context, View linearLayoutView) {
savedContext = context;
savedLinearLayoutView = linearLayoutView;
if (count < 8) {
EditText editText = new EditText(context);
LinearLayout linearLayoutObjectives = (LinearLayout) linearLayoutView;
editText.setId(R.id.edit_text_);
linearLayoutObjectives.addView(editText);
count++;
}
}
public void restoreFragment(){
for(int i=0; i<count;i++){
EditText editText = new EditText(savedContext);
LinearLayout linearLayoutObjectives = (LinearLayout) savedLinearLayoutView;
editText.setId(R.id.edit_text_);
linearLayoutObjectives.addView(editText);
count++;
}
}
public int getCount() {
return count;
}
}
getCount將()總是得到0 謝謝您的幫助:)
我建議您創建一個「邏輯」對象的Parcelable版本,以便您可以保存它並恢復到狀態宗地。你的「邏輯」對象不應該從任何活動類繼承,如果它不是一個真正的活動,那麼你只是以這種方式沒有真正的理由而燒着內存。不要爲編程創建的視圖設置id,這是沒有意義的,因爲id僅用於彌合XML-Code差距。儘量不要拘泥於Context實例,因爲它會導致嚴重的內存泄漏。 – Machinarius
謝謝Machinarius! –
總是樂意幫忙 – Machinarius