android之SharedPreferences函数的运用

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();

    }
}
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值