Android Swich的基本用法,保存状态等

今天用了Swich控件,其实挺简单和Button基本用法差不多,基本的使用就不多介绍了,现在就是如何保存他的状态,用SharedPreferences 来保存状态就可以实现了,然后就写自己的逻辑就可以了,代码如下:

 private void SwichState() {
        try {
            final boolean falg = true;
            SharedPreferences preferences;
            aSwitch = (Switch) findViewById(R.id.switch1);

            // 从SharedPreferences获取数据:
            preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
            if (preferences != null) {
                boolean name = preferences.getBoolean("flag", falg);
                aSwitch.setChecked(name);
            }
            aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        //将数据保存至SharedPreferences:
                        SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putBoolean("flag", true);
                        editor.commit();
                    } else {
                        //将数据保存至SharedPreferences:
                        SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putBoolean("flag", false);
                        editor.commit();

                    }
                }
            });

你可能感兴趣的:(Android)