Home > Software design >  Why the on checked change listener cannot working
Why the on checked change listener cannot working

Time:09-03

This is the code, the CompoundButton.OnCheckedChangeListener() cannot working

//Assign variable

    switchCompat = findViewById(R.id.bt_switch);

    switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckChanged(CompoundButton buttonView, boolean isChecked) {
            //Checked condition
            if (isChecked) {
                //when switch button is checked
                //set night mode
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            } else {
                //when switch button is unchecked
                //set light mode
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            }
        }
    });

CodePudding user response:

You used the wrong function you should use

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

in the code it will look like this

switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // Checked condition
                if (isChecked) {
                    //when switch button is checked
                    //set night mode
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                } else {
                    //when switch button is unchecked
                    //set light mode
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                }
            }
        });
  • Related