Android学习之SharedPreferences
SharedPreferences使用键值对的方式来存储数据,并支持多种不同类型的数据存储。
1、界面布局
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:stretchColumns="0"> <!-- 拉伸第1列 -->
<TableRow>
<EditText
android:id="@+id/txtWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:hint="请输入" />
<Button
android:id="@+id/btnWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="写入" />
</TableRow>
<TableRow>
<TextView
android:id="@+id/txtRead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="@+id/btnRead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取" />
</TableRow>
</TableLayout>
2、代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnWrite = (Button) findViewById(id.btnWrite);
btnWrite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText txtEditText = (EditText) findViewById(R.id.txtWrite);
String string = txtEditText.getText().toString();
//MODE_PRIVATE和传入0相同,表示只有当前应用程序才能对这个SharedPreferences文件进行操作
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name", string);
editor.commit();
}
});
Button btnRead = (Button) findViewById(id.btnRead);
btnRead.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
String string = sharedPreferences.getString("name", "");
TextView textView = (TextView) findViewById(R.id.txtRead);
textView.setText(string);
}
});
}
}
可以通过DDMS导出生成的文件。
文件内容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">张三</string>
</map>
最新文章
- C#异常处理性能测试
- CocoaPods使用 主要带图。转载。
- POJ 2411 Mondriaan&;#39;s Dream
- 【初级为题,大神绕道】The app icon set named "AppIcon" did not have any applicable content 错误#解决方案#
- linux内核中创建线程方法
- 三个流行MySQL分支的对比
- 使用BOOST BIND库提高C++程序性能
- 关于PHP参数的引用传递和值传递
- iso18092-2004中ISO14443,Felica的关系
- Scala Hello 示例
- c#正则表达式应用实例
- 【Swfit】Swift与OC两种语法写单例的区别
- 清理maven本地库中的lastUpdated文件
- 数据库 -- mysql记录操作
- Ubuntu修改时间时区
- 无法外网访问VM中的hadoop yarn的8088端口
- Android实践项目汇报(三)
- 洛谷 P4011 孤岛营救问题【最短路+分层图】
- C#中的 .NET 弱事件模式
- Python爬虫基础(二)urllib2库的get与post方法
热门文章
- [CTCI] 单词最近距离
- 事件,委托,action与func文章不错的
- WCF学习分享2
- docker 安装MySQL远程连接
- angular学习笔记(三十)-指令(7)-compile和link(2)
- 京东轮播图片的静态页面CSS3
- Lua string.gsub (s, pattern, repl [, n])
- 【Android】HAL分析
- 【内核】linux2.6版本内核编译配置选项(一)
- Linux命令格式及帮助命令详解