检查android复选框始终为true

时间:2015-09-29 18:18:54

标签: android eclipse checkbox

我定义了一个复选框并且没有为其分配任何值 每次我点击它并打印复选框的值时,每次都会显示true

我将结果放在SharedPreferences中然后检索它 为什么总是true

public class CallAndSms extends Activity{
static SQLiteDatabase myDB= null;
static     Context context ;
static ListView lv;
static CallAndSmsAdaptor adapter;
static ArrayList<String> AllData= new ArrayList<String>();
CheckBox save;
static SharedPreferences preferences;
SharedPreferences.Editor editor=null;
 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);





    setContentView(R.layout.sms_call);
     preferences = getSharedPreferences("modes",Context.MODE_PRIVATE);
     editor = preferences.edit();



    save= (CheckBox) findViewById(R.id.save);


    save.setChecked(preferences.getBoolean("save", true));



    context=this;


     save.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

            if ( save.isChecked()){
                Log.i("save save", save.isChecked()+"");

                  editor.putBoolean("save", true);

            }

            else 

                  {editor.putBoolean("save", false);}

            Log.i("pref", preferences.getBoolean("save", true)+"");


        }
    });


 }
 }

2 个答案:

答案 0 :(得分:4)

您永远不会apply()(或commit())您的偏好更改 因此,您始终可以检索默认值。

答案 1 :(得分:1)

编辑后,您必须提交 shared preferences

save.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
           if ( save.isChecked()){
              Log.i("save save", save.isChecked()+"");
              editor.putBoolean("save", true);
              editor.commit();
           }else{
              editor.putBoolean("save", false);
              editor.commit();
           }
              Log.i("pref", preferences.getBoolean("save", true)+"");
        }
    });