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