package com.example.chapter3; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; public class ShareWriteActivity extends AppCompatActivity implements View.OnClickListener { private EditText et_name; private EditText et_age; private EditText et_height; private EditText et_weight; private SharedPreferences preference; private CheckBox ck_married; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_share_write); et_name = findViewById(R.id.et_name); et_age = findViewById(R.id.et_age); et_height = findViewById(R.id.et_height); et_weight = findViewById(R.id.et_weight); ck_married = findViewById(R.id.ck_married); findViewById(R.id.bth_save).setOnClickListener(this); preference = getSharedPreferences("config", Context.MODE_PRIVATE); reload(); } private void reload() { String name = preference.getString("name", null); if(name !=null){ et_name.setText(name); } int age = preference.getInt("age", 0); if(age != 0){ et_age.setText(String.valueOf(age)); } float height = preference.getFloat("height", 0f); if(height != 0f){ et_height.setText(String.valueOf(height)); } float weight = preference.getFloat("weight", 0f); if(weight != 0f){ et_weight.setText(String.valueOf(weight)); } boolean ck_married1 = preference.getBoolean("ck_married", false); ck_married.setChecked(ck_married1); } @SuppressLint("ApplySharedPref") @Override public void onClick(View v) { String name=et_name.getText().toString(); String age=et_age.getText().toString(); String height=et_height.getText().toString(); String weight=et_weight.getText().toString(); //获取它的编辑器 SharedPreferences.Editor editor = preference.edit(); editor.putString("name",name); editor.putInt("age",Integer.parseInt(age)); editor.putFloat("height",Float.parseFloat(height)); editor.putFloat("weight",Float.parseFloat(weight)); editor.putBoolean("ck_married",ck_married.isChecked()); //这是提交按钮 editor.commit(); } }
android之SharedPreferences函数的运用
于 2024-08-20 16:22:46 首次发布