The example shows how to persistently save user preferences when the program is closed.
@ Override
Protected void onResume (){
Super. onResume ();
SharedPreferences prefs = getPreferences (0 );
String restoredText = prefs. getString ("text", null );
If (restoredText! = Null ){
MSaved. setText (restoredText, TextView. BufferType. EDITABLE );
Int selectionStart = prefs. getInt ("selection-start",-1 );
Int selectionEnd = prefs. getInt ("selection-end",-1 );
If (selectionStart! =-1 & selectionEnd! =-1 ){
MSaved. setSelection (selectionStart, selectionEnd );
}
}
}
1. Restore the status in the onResume method. To run the program, this method must be executed.
2. SharedPreferences stores information in key/value mode.
3. setSelection: Set the cursor and selection information.
Www.2cto.com
@ Override
Protected void onPause (){
Super. onPause ();
SharedPreferences. Editor editor = getPreferences (0). edit ();
Editor. putString ("text", mSaved. getText (). toString ());
Editor. putInt ("selection-start", mSaved. getSelectionStart ());
Editor. putInt ("selection-end", mSaved. getSelectionEnd ());
Editor. commit ();
}
1.
Save the status in the onPause method, because this method is executed no matter how the program is closed. 2. The onSaveInstanceState () method can also be used, but this method is generally used to save the UI state. 3. SharedPreferences. Editor is used to save information. The commit method submits the saved information. Switch between portrait and landscape screens: