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

此外的一个方法是使用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):

    /**
* Any time we are paused we need to save away the current state, so it
* will be restored correctly when we are resumed.
*/
@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();
}

读取Shared Preference: pref.getXXX(key)

    /**
* Upon being resumed we can retrieve the current state. This allows us
* to update the state if it was changed at any time while paused.
*/
@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);
}
}
}

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

最新文章

  1. [linux-内核][转]内核日志及printk结构浅析
  2. networkx的绘图中文显示方块问题
  3. angularjs的ng-repeat指令下的scope作用域
  4. 多功能节点连线绘图控件Nevron Diagram for .NET使用方法及下载地址
  5. 【效率】FIND
  6. 【腾讯开源】Android性能测试工具APT使用指南
  7. webpack1 新手入门教程
  8. 关于classpath
  9. ●BZOJ 3622 已经没有什么好害怕的了
  10. sqoop的基本语法详解及可能遇到的错误
  11. [Spark][Python]Wordcount 例子
  12. xampp默认mysql数据库root密码的修改
  13. did not call through to super.onCreate()
  14. 单变量微积分笔记21——三角替换2(tan和sec)
  15. UE如何使用正则表达式
  16. mac终端 login: login: Could not determine audit condition
  17. 洛谷P3066 [USACO12DEC] 逃跑的Barn [左偏树]
  18. 【51Nod 1238】最小公倍数之和 V3
  19. jQuery实现表格冻结行和列
  20. hihoCoder#1122(二分图最大匹配之匈牙利算法)

热门文章

  1. memcache_helper
  2. vue学习二:
  3. STM32F030 使用硬件 SPI
  4. Codeforces-B-Divisors of Two Integers(思维技巧)
  5. php返回数据格式
  6. Java实现范围内随机数
  7. aerospike(2)-java client
  8. python学习3(转载)
  9. JOIN 和 NULL
  10. tail -f 实时跟踪一个日志文件的输出内容