Android核心技术-day02-08-settings

版权声明:心灵泽尘 https://blog.csdn.net/github_38313789/article/details/83756734
package com.gaozewen.setting;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private CheckBox cb;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cb = findViewById(R.id.cb);
        sp = getSharedPreferences("config", MODE_PRIVATE);

        // 回显数据
        boolean status = sp.getBoolean("status", false);
        cb.setChecked(status);

        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
//                Toast.makeText(MainActivity.this,"setOnCheckedChangeListener",Toast.LENGTH_SHORT).show();
                if(isChecked){
                    // 去设置 EditText 的内容
                }
                SharedPreferences.Editor edit = sp.edit();
                edit.putBoolean("status",isChecked);
                edit.apply(); // 应用数据 类似关闭流 事务
            }
        });

        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this,"setOnClickListener",Toast.LENGTH_SHORT).show();
                // 这里需要调用方法,上面直接调用的参数
                cb.isChecked();
            }
        });
    }
}

猜你喜欢

转载自blog.csdn.net/github_38313789/article/details/83756734