<?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">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是一个按钮" />
<Button
android: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方法
* */
@Override
protected 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);
}
/**
* 根据不同的按钮,触发不同的逻辑,
* */
@Override
public 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;
}
}
}