Saving TextView with onSaveInstanceState

2019-05-14 01:38发布

问题:

I'm trying for hours to save & restore TextView and Buttons. It seems that I'm not able to save TextView because "outState" requires a String.

I made a TicTacToe game but I want to save all the stuffs when orientation is "landscape"

Here is a part of what I'm trying to do :

private Button lesBoutons[];
private Button rejouer;
private Jeu jeu;
private TextView leTexte;
private int[] tabGagne;
public boolean fini;

@Override
public void onSaveInstanceState(Bundle outState) {
   super.onSaveInstanceState(outState);
   outState.PutString("savText", leTexte);
   //TextView savTexte = leTexte;
   //String phrase=leTexte.toString();
   //outState.putString("TEST", phrase);
   //leTexte.getResources();
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
 super.onRestoreInstanceState(savedInstanceState);
// leTexte.setText(savedInstanceState.getString("TEST"));
}

How can I save this TextViews and all the buttons ?

回答1:

Do a leTexte.getText(). That will get you the text, but make sure you initialize the TextView object first.



回答2:

Android calls onSaveInstanceState() before it destroys your activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState().

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("savText", leTexte.getText().toString());
//save the state
//1st parameter is the key
//2nd parameter is the value
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
leTexte.setText(savedInstanceState.getString("savText"));
//restore it using the key
}

Also have look at the link below.

http://developer.android.com/guide/topics/resources/runtime-changes.html