Android ApiDemo示例解读9:Activity->Persistent State

移动开发 Android
App->Activity->Persistent State使用了Shared Preferences来保持部分UI状态(TextView的值)。创建或是修改Shared Preferences,使用getSharedPreferences(String name, int mode)方法。Shared Preferences 用于单个Application不同Activity之间共享一些数据,单不能用于不同Application之间共享数据。

Android 提供了多种存储数据的方法,其中最简单的是使用Shared Preferences。Shared Preferences 可以存储 Key/value 对,Shared Preferences 支持存取 boolean, float ,long ,integer, string ,最常用的使用Shared Preferences是用来存储一些应用偏好。此外的一个方法是使用onSaveInstanceState(),这是特别用来保存UI 状态的。

App->Activity->Persistent State使用了Shared Preferences来保持部分UI状态(TextView的值)。

创建或是修改Shared Preferences,使用getSharedPreferences(String name, int mode)方法。Shared Preferences 用于单个Application不同Activity之间共享一些数据,单不能用于不同Application之间共享数据。

SharedPreferences.Editor 用来给Shared Preferences添加数据: editor.putXXX(key,value)

  1. protected void onPause() {   
  2. super.onPause();   
  3.     
  4. SharedPreferences.Editor editor = getPreferences(0).edit();   
  5. editor.putString("text", mSaved.getText().toString());   
  6. editor.putInt("selection-start", mSaved.getSelectionStart());   
  7. editor.putInt("selection-end", mSaved.getSelectionEnd());   
  8. editor.commit();   
  9. }   

读取Shared Preference: pref.getXXX(key)

  1. protected void onResume() {   
  2. super.onResume();   
  3.     
  4. SharedPreferences prefs = getPreferences(0);   
  5. String restoredText = prefs.getString("text"null);   
  6. if (restoredText != null) {   
  7. mSaved.setText(restoredText, TextView.BufferType.EDITABLE);   
  8.     
  9. int selectionStart = prefs.getInt("selection-start", -1);   
  10. int selectionEnd = prefs.getInt("selection-end", -1);   
  11. if (selectionStart != -1 && selectionEnd != -1) {   
  12. mSaved.setSelection(selectionStart, selectionEnd);   
  13. }   
  14. }   
  15. }   

Android ApiDemo示例解读系列之九:App->Activity->Persistent State

Persistent State 演示了如何使用Shared Preferences在Activity 恢复时保持EditText的内容。 单是更一般的方法是使用onSaveInstanceState。

责任编辑:闫佳明 来源: jizhuomi
相关推荐

2013-12-19 14:32:31

Android ApiAndroid开发Android SDK

2013-12-19 14:34:52

Android ApiAndroid开发Android SDK

2013-12-19 14:16:46

Android ApiAndroid开发Android SDK

2013-12-19 14:13:16

Android ApiAndroid开发Android SDK

2013-12-19 14:28:04

Android ApiAndroid开发Android SDK

2013-12-19 14:00:39

Android ApiAndroid开发Android SDK

2013-12-19 13:40:44

Android ApiAndroid开发Android SDK

2013-12-19 13:51:12

Android ApiAndroid开发Android SDK

2013-12-19 16:26:29

Android ApiAndroid开发Android SDK

2014-05-27 15:07:07

AndroidActivitysingleTask

2010-02-02 14:22:50

Python示例

2010-02-01 11:22:09

C++虚函数

2012-02-17 17:07:30

Android安全Activity劫持

2015-10-20 15:54:16

android源码滑动关闭

2010-03-05 10:47:05

Python futu

2010-03-02 14:41:00

WCF行为控制

2013-01-08 13:33:07

Android开发Activity入门指南

2014-08-08 10:36:12

ActivityAndroid

2011-04-12 17:16:52

Activity跳转开发实例Android学习笔记

2011-06-02 11:13:10

Android Activity
点赞
收藏

51CTO技术栈公众号