java文件
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public Button saveData;
public Button seeData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saveData=(Button)findViewById(R.id.save_data);
seeData=(Button)findViewById(R.id.see_data);
saveData.setOnClickListener(this);
seeData.setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()){
case R.id.save_data:
SharedPreferences.Editor editor=getSharedPreferences("data",MODE_APPEND).edit();//写操作,获取SharedPrefeferences.Edito对象。
editor.putBoolean("is_login",true);//键值对存储
editor.putString("name","Tom");
editor.putInt("age",20);
editor.putBoolean("married",false);
editor.commit();
Toast.makeText(MainActivity.this,"hello",Toast.LENGTH_LONG).show();
break;
case R.id.see_data:
SharedPreferences pref=getSharedPreferences("data",MODE_APPEND);/*data为文件名,MODE_APPEND为操作模式。
int age=pref.getInt("age",0);
String name=pref.getString("name","00");
Log.d("MainActivity","name is"+name);
Log.d("MainActivity","age is"+age);
}
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/save_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="存储"
/>
<Button
android:id="@+id/see_data"
android:text="读取"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>