Android API Demos Learning (3)-Persistent State

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.