简体   繁体   中英

Get checkbox status as soon as it is checked or unchecked

I want to get the current status of checkbox as soon as it is check or unchecked. Based on that show the Toast message. Here is my code so far.

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean Alarm = getPrefs.getBoolean("cbAlarm", true);
    if(Alarm == true) {
        Toast.makeText(this, "Checked", Toast.LENGTH_LONG).show();
    } else if(Alarm == false) {
        Toast.makeText(this, "UnChecked", Toast.LENGTH_LONG).show();
    }

How can I achieve this. Please help.

Edit here is my xml file

<CheckBoxPreference
    android:title="Enable/Disable Alarm"
    android:defaultValue="true"
    android:key="cbAlarm"
    android:summary="Enable or disable alarm" />

Just implement OnCheckedChangeListener:

CheckBox myCheckBox = (CheckBox)  findViewById(R.id.my_checkbox);

myCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
        if (isChecked){
             Toast.makeText(this, "Checked", Toast.LENGTH_LONG).show();
        }else{
             Toast.makeText(this, "UnChecked", Toast.LENGTH_LONG).show();
        }  
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM