6

I need to disable swipe in switch compat.I am using OnclickListener for toggling the switch.I have implemented some functionality for onClickListener.But when the user swipes the toggle he is not getting the implemented functionality.I need to disable swipe for switch compat.

Note: I am not using onCheckedlistener since I was getting some issues withonCheckedListener.

<android.support.v7.widget.SwitchCompat
    android:id="@+id/switchButton"
    android:layout_width="wrap_content"
    android:layout_centerInParent="true"
    android:checked="false"
    android:scrollbarAlwaysDrawVerticalTrack="true"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Switch example"
    />

SwitchCompat switchCompat;
switchCompat=(SwitchCompat)findViewById(R.id.switchButton);
     switchCompat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(), "toggled", Toast.LENGTH_SHORT).show(); //added
        }
    });
4
  • @Aks4125 :That solution did not help me Feb 15, 2018 at 7:01
  • 1
    Then you should mention in your question about research. As you can see below answer by AJ is identical from the same post. :)
    – Aks4125
    Feb 15, 2018 at 7:03
  • Accepted answer is available in duplicate question. I am saying here because you said that question didn't solve your problem.. stackoverflow.com/a/21126040/4647628
    – Aks4125
    Feb 15, 2018 at 9:05
  • You can do this switchBtn.isClickable = false Nov 29, 2022 at 7:23

2 Answers 2

5

Try to prevent switch class from receiving swipe events by using the following code:

switchBtn.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return event.getActionMasked() == MotionEvent.ACTION_MOVE;
    }
});

this may prevent the switch from receiving the swipe

2
  • 1
    Thanks it worked like a charm Feb 15, 2018 at 8:53
  • Thanks , I want to perform action on OnClick , not on OnCheckChanged. it worked for me. Jan 11, 2019 at 7:35
1

use TouchListener

switchButton.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(p0: View, p1: MotionEvent): Boolean {
                when (p1.action) {
                    MotionEvent.ACTION_DOWN -> {
                        return false
                    }
                    MotionEvent.ACTION_UP -> {
                        return false
                    }
                    MotionEvent.ACTION_MOVE -> {
                        return true
                    }
                    else -> {
                        return true
                    }
                }
            }
        })

now you cant swipe switch

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.