SharedPreferences的基本数据写入和读取

1、布局

 
   
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <Button
  7. android:id="@+id/btn"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:text="我是一个按钮" />
  11. <Button
  12. android:id="@+id/btn1"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:text="恢复数据吧少年" />
  16. </LinearLayout>


2、java文件

 
   
  1. package lpc.com.project631;
  2. import android.app.Activity;
  3. import android.content.SharedPreferences;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.Button;
  7. import android.widget.Toast;
  8. /**
  9. * Created by Administrator on 2016/1/7.
  10. */
  11. public class MainActivity1 extends Activity implements View.OnClickListener{
  12. /**
  13. * oncreate方法里很简单,只有两个按钮,绑定了OnClick方法
  14. * */
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. Button button = (Button) findViewById(R.id.btn);
  20. Button button1 = (Button) findViewById(R.id.btn1);
  21. button.setOnClickListener(this);
  22. button1.setOnClickListener(this);
  23. }
  24. /**
  25. * 根据不同的按钮,触发不同的逻辑,
  26. * */
  27. @Override
  28. public void onClick(View v) {
  29. switch (v.getId()){
  30. case R.id.btn:
  31. SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
  32. editor.putString("name","刘朋程");
  33. editor.putInt("age",28);
  34. editor.apply();
  35. break;
  36. case R.id.btn1:
  37. SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
  38. String name = pref.getString("name","李莉");
  39. int age = pref.getInt("age",27);
  40. Toast.makeText(MainActivity1.this,"我的名字是" + name + "我的年龄是" +
  41. age,Toast.LENGTH_SHORT).show();
  42. break;
  43. default:
  44. break;
  45. }
  46. }
  47. }





转载于:https://www.cnblogs.com/liupengcheng/p/5126307.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值