Search code examples
androidontouchlistenertouch-eventontouchandroid-switch

how to skip switch.setOnCheckedChangeListener when status is not updated by user


since i am trying the switch first time (new to android) i am not sure how to handle this issue. i have a switch on an activity and an attached setOnCheckedChangeListener() to it. when the activity's oncreate is called i make an async call to database and depending on the values received i set the status of the switch on/off. Now the problem is that however i am setting the switch state to just show whats its current status on db and no user has changed it yet, still the listner function is called. i know that the code is working correctly but with the state changed listner i need something else to confirm that the state has been changed by the user . i think onTouchEvent(MotionEvent event) can fill the purpose but do not know hot to use it in conjuction with switch.setOnCheckedChangeListener

does anyone know of any better solution to it or atleast can help me telling how to use ontouch even with listner...

sw_recording_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   }}

thanks !!!


Solution

  • Indeed when calling Switch.setChecked(boolean); the OnCheckedChangeListener will be triggerd as well. The way I overcame this problem was to use a flag and set it to false before I call setChecked()

    This way the listener will still be called when you programmatically use setChecked() but the code inside won't execute, unless a user presses on the switch.

        //prevent the code from listener to run, flag set to false before calling setChecked(true);
        should_run = false;
        toggle_facebook.setChecked(true);
    
        ....
    
        private OnCheckedChangeListener onSwitchSlided = new OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                switch(buttonView.getId())
                {
                    case R.id.settings_toggle_facebook:
                    {
                        if(true == should_run)
                        {
                            //do stuff
                        }
    
                        should_run = true;
                        break;
                    }
                    case R.id.settings_toggle_twitter:
                    {
                        if(true == should_run)
                        {
                            //do stuff
                        }
    
                        should_run = true;
                        break;
                    }
                }
            }
        };