28. SharedPreferences的使用
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button button;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn_get);
button.setOnClickListener(this);
SharedPreferences preferences = getSharedPreferences("data", MODE_PRIVATE);
if (preferences != null) {
Log.d(TAG, "onCreate: "+preferences.getString("name",""));
Log.d(TAG, "onCreate: "+preferences.getInt("age",0));
Log.d(TAG, "onCreate: "+preferences.getBoolean("married",false));
}
}
private void save() {
SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("name","Tom");
editor.putInt("age",28);
editor.putBoolean("married",false);
editor.apply();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_get:
save();
break;
default:
break;
}
}
}
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_get"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存文件"/>
</LinearLayout>