如何在SwitchCompat小部件中侦听状态更改?

时间:2014-11-16 08:10:27

标签: android android-appcompat

如何监听SwitchCompat小部件点击?我想在切换Switch时执行一些语句。

寻找等效的

button.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View view) {
        //Do something
    }
});

6 个答案:

答案 0 :(得分:48)

static Boolean isTouched = false;

switchButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                isTouched = true;
                return false;
            }
        });

switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if (isTouched) {
                isTouched = false;
                if (isChecked) {
                }
                else {
                }
            }
        }
    });

试试这个!

答案 1 :(得分:7)

你只需要这个(不需要setOnTouchListener):

switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {

                if (isChecked) {
                     //if 'isChecked' is true do whatever you need...
                }
                else {
                }
            }
        }
    });

答案 2 :(得分:0)

使用Butterknife SwitchCompat状态更改

@OnCheckedChanged(R.id.switchCompat)
        public void onCheckedChanged(SwitchCompat switchCompat, boolean isChecked){
            Log.i("skh","check:"+isChecked);

            if (isChecked) {
               // Log.i("skh","check:"+isChecked);
            }
            else {

            }

答案 3 :(得分:0)

我对Slay在接受的答案的评论中也遇到了同样的问题。解决方法在这里!

我的解决方案,使用SwitchCompat和Kotlin。在我的情况下,仅当用户通过UI触发更改时,我才需要对更改做出反应。实际上,我的开关对LiveData有反应,这使得setOnClickListenersetOnCheckedChangeListener都无法使用。 setOnClickListener实际上对用户交互做出正确反应,但是如果用户在开关上拖动拇指则不会触发。如果以编程方式(例如,由观察者)切换了开关,则另一端的setOnCheckedChangeListener也将被触发。现在,在我的情况下,该开关位于两个片段上,因此在某些情况下,onRestoreInstanceState会触发带有旧值的开关覆盖正确的值。

因此,我查看了SwitchCompat的代码,并成功地模仿了它在区分单击和拖动方面的行为,并使用它来构建了一个可以正常工作的自定义触摸侦听器。我们开始:

/**
 * This function calls the lambda function passed with the right value of isChecked
 * when the switch is tapped with single click isChecked is relative to the current position so we pass !isChecked
 * when the switch is dragged instead, the position of the thumb centre where the user leaves the
 * thumb is compared to the middle of the switch, and we assume that left means false, right means true
 * (there is no rtl or vertical switch management)
 * The behaviour is extrapolated from the SwitchCompat source code
 */
class SwitchCompatTouchListener(private val v: SwitchCompat, private val lambda: (Boolean)->Unit) :  View.OnTouchListener {
    companion object {
        private const val TOUCH_MODE_IDLE = 0
        private const val TOUCH_MODE_DOWN = 1
        private const val TOUCH_MODE_DRAGGING = 2
    }

    private val vc = ViewConfiguration.get(v.context)
    private val mScaledTouchSlop = vc.scaledTouchSlop
    private var mTouchMode = 0
    private var mTouchX = 0f
    private var mTouchY = 0f

    /**
     * @return true if (x, y) is within the target area of the switch thumb
     * x,y and rect are in view coordinates, 0,0 is top left of the view
     */
    private fun hitThumb(x: Float, y: Float): Boolean {
        val rect = v.thumbDrawable.bounds
        return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
    }

    override fun onTouch(view: View, event: MotionEvent): Boolean {
        if (view == v) {
            when (MotionEventCompat.getActionMasked(event)) {
                MotionEvent.ACTION_DOWN -> {
                    val x = event.x
                    val y = event.y
                    if (v.isEnabled && hitThumb(x, y)) {
                        mTouchMode = TOUCH_MODE_DOWN;
                        mTouchX = x;
                        mTouchY = y;
                    }
                }
                MotionEvent.ACTION_MOVE -> {
                    val x = event.x
                    val y = event.y
                    if (mTouchMode == TOUCH_MODE_DOWN &&
                        (abs(x - mTouchX) > mScaledTouchSlop || abs(y - mTouchY) > mScaledTouchSlop)
                    )
                        mTouchMode = TOUCH_MODE_DRAGGING;
                }
                MotionEvent.ACTION_UP,
                MotionEvent.ACTION_CANCEL -> {
                    if (mTouchMode == TOUCH_MODE_DRAGGING) {
                        val r = v.thumbDrawable.bounds
                        if (r.left + r.right < v.width) lambda(false)
                        else lambda(true)
                    } else lambda(!v.isChecked)
                    mTouchMode = TOUCH_MODE_IDLE;
                }
            }
        }
        return v.onTouchEvent(event)
    }
}

如何使用它:

实际的监听器接受带有代码的lambda来执行:

myswitch.setOnTouchListener(
    SwitchCompatTouchListener(myswitch) {
        // here goes all the code for your callback, in my case
        // i called a service which, when successful, in turn would 
        // update my liveData 
        viewModel.sendCommandToMyService(it) 
    }
)

为了完整起见,状态switchstate(如果有)的观察者是这样的:

switchstate.observe(this, Observer {
    myswitch.isChecked = it
})

答案 4 :(得分:0)

现在可以在同一回调中使用isPressed方法进行检查了。

    switchCompat.setOnCheckedChangeListener { buttonView, isChecked ->
        if (buttonView?.isPressed == true) {
            // todo
        } else {
            
        }
    }

答案 5 :(得分:0)

实际上,你只需要这个:

if (yourSwitchButton.isChecked()) {
//do what you want here
} else{
//do what you want here
}

仅此而已!