Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for state change in SwitchCompat widget?

How to listen for SwitchCompat widget clicks? I want to execute a few statements when the Switch is toggled.

Looking for an equivalent of

button.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View view) {
        //Do something
    }
});
like image 268
Slay Avatar asked Nov 16 '14 08:11

Slay


3 Answers

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 {
                }
            }
        }
    });

Try this!

like image 199
Konstantin Loginov Avatar answered Nov 08 '22 12:11

Konstantin Loginov


you need only this(the setOnTouchListener is unnecessary):

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

                if (isChecked) {
                     //if 'isChecked' is true do whatever you need...
                }
                else {
                }
            }
        }
    });
like image 12
batsheva Avatar answered Nov 08 '22 10:11

batsheva


With Butterknife SwitchCompat state change

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

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

    }
}
like image 5
Shomu Avatar answered Nov 08 '22 12:11

Shomu