Search code examples
androidandroid-switch

android Switch not toggling programmatically


I am trying to toggle a switch back to the off state programmatically, however I am running into a problem.

I have tried using both myswitch.setischecked(false) and myswitch.toggle and they both leave the switch on the current state but change the background from blue to grey, so android thinks the switch is off, however the display doesn't reflect this.

Here is my code

  final Switch InstaPrint = (Switch) rootView.findViewById(R.id.instaprint);
        final Switch MyZebraSwitch = (Switch) rootView.findViewById(R.id.myzebraswitch);
        final Switch StockZebraSwitch = (Switch) rootView.findViewById(R.id.stockzebraswitch);
        final Switch StoreZebraSwitch = (Switch) rootView.findViewById(R.id.storezebraswitch);

        final Spinner MyZebraSpinner = (Spinner) rootView.findViewById(R.id.myzebraspinner);
        final Spinner StockZebraSpinner = (Spinner) rootView.findViewById(R.id.stockzebraspinner);
        final Spinner StoreZebraSpinner = (Spinner) rootView.findViewById(R.id.storezebraspinner);


        //InstantPrint

        InstaPrint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(InstaPrint.isChecked())
                {
                    if(!MyZebraSwitch.isChecked() && !StockZebraSwitch.isChecked() && !StoreZebraSwitch.isChecked())
                    {

                        Vibrator vib = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
                        vib.vibrate(1000);
                       // PlayFile("bell.mp3");
                        Toast toast = Toast.makeText(getActivity(), "You must select at least one printer", Toast.LENGTH_LONG);
                        toast.show();
                        InstaPrint.toggle();
                    }
                }
            }
        });

Anyone else suffered from this?

EDIT - After playing around I discovered that changing the orientation of my device corrects the problem, my switches are contained with a fragment, so a redraw of the fragment appears to correct it, now just need to work out how to redraw programmatically!


Solution

  • It seems a bit counter intuitive to call either the toggle() or setChecked(boolean) methods inside of a state listener. I would expect some sort of infinite loop or weird behavior because you programmatically change the state inside of a state changed callback. I would try using the setOnClickListener(View.OnClickListener) method inherited from the View class instead.