Search code examples
androideventsdelaytogglebutton

delay switch state on togglebutton click


I need to delay the switching of the state of a togglebutton when I click on it. I have to do some operation and than when another event is called the state of the togglebutton have to change. How can I do that? Thanks!


Solution

  • Subclass the ToggleButton and override the click handling. Use an AsyncTask to accomplish your task and then do the actual toggling by calling super.performClick() when you want to actually perform the toggling.

    public class MyToggleButton extends ToggleButton {
    
        public MyToggleButton(Context context) {
            super(context);
        }
    
        public MyToggleButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public MyToggleButton(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        public boolean performClick() {
            // do your thing here
    
                // only call the below line if you actually want it to happen.
            return super.performClick();
        }
    }