SharedPreferences的基本数据写入和读取
1、布局
![]()
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><Buttonandroid:id="@+id/btn"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="我是一个按钮" /><Buttonandroid:id="@+id/btn1"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="恢复数据吧少年" /></LinearLayout>

2、java文件
package lpc.com.project631;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;/*** Created by Administrator on 2016/1/7.*/public class MainActivity1 extends Activity implements View.OnClickListener{/*** oncreate方法里很简单,只有两个按钮,绑定了OnClick方法* */@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button button = (Button) findViewById(R.id.btn);Button button1 = (Button) findViewById(R.id.btn1);button.setOnClickListener(this);button1.setOnClickListener(this);}/*** 根据不同的按钮,触发不同的逻辑,* */@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.btn:SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();editor.putString("name","刘朋程");editor.putInt("age",28);editor.apply();break;case R.id.btn1:SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);String name = pref.getString("name","李莉");int age = pref.getInt("age",27);Toast.makeText(MainActivity1.this,"我的名字是" + name + "我的年龄是" +age,Toast.LENGTH_SHORT).show();break;default:break;}}}

浙公网安备 33010602011771号