SwitchButton icon indicating copy to clipboard operation
SwitchButton copied to clipboard

需要在onCheckedChanged中切换状态,应该怎么实现?

Open chengxp opened this issue 8 years ago • 3 comments

比如有这么一个需求,点击switch开关,点击后会有个网络请求,需要根据请求返回的状态来设置这个开关的状态,这样的话就需要在onCheckedChanged中使用setChecked(isChecked)方法,可是这种方式被弄成异常抛出了,请问是否有其他方式可以实现?

chengxp avatar Jul 18 '17 07:07 chengxp

修改源码,能解决点击切换,滑动切换没试过

    private void toggle(boolean animate, boolean broadcast) {
        if(!isEnabled()){return;}

        if(isEventBroadcast){
            throw new RuntimeException("should NOT switch the state in method: [onCheckedChanged]!");
        }

改成

    private void toggle(boolean animate, boolean broadcast) {
        if(!isEnabled()){return;}

        if(isEventBroadcast){
            if(!isChecked()){
                setCheckedViewState(viewState);
            }else{
                setUncheckViewState(viewState);
            }
            isChecked=!isChecked();
            postInvalidate();
            return;
        }

nhtzj avatar Sep 21 '17 08:09 nhtzj

一定要改源码才能实现么

KXHNR avatar Apr 23 '20 03:04 KXHNR

我的解决方案是 使用在 onCheckedChanged 中使用view.post{ //TODO } 可以实现

wenvelope avatar Jun 24 '22 16:06 wenvelope