Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch button - disable swipe function

Tags:

android

I have a switch button (actually is a custom one) and I want to disable the swipe functionality for some reason; I want the user to be able to click it only. Is there a way to achieve this? Thanks.

like image 562
Paul Avatar asked Dec 10 '12 16:12

Paul


People also ask

How to disable switch button in Android studio?

You can setClickable(false) to your Switch, then listen for the onClick() event within the Switch's parent and toggle it programmatically. The switch will still appear to be enabled but the swipe animation won't happen. Switch switchInternet = (Switch) findViewById(R.

How do I disable Home button on Android?

Open your phone's Settings app. Swipe up on Home button. Turn Swipe up on Home button off or on.


2 Answers

You can setClickable(false) to your Switch, then listen for the onClick() event within the Switch's parent and toggle it programmatically. The switch will still appear to be enabled but the swipe animation won't happen.

...

[In onCreate()]

Switch switchInternet = (Switch) findViewById(R.id.switch_internet); switchInternet.setClickable(false); 

...

[click listener]

public void ParentLayoutClicked(View v){     Switch switchInternet = (Switch) findViewById(R.id.switch_internet);      if (switchInternet.isChecked()) {         switchInternet.setChecked(false);                } else {         switchInternet.setChecked(true);         }        } 

...

[layout.xml]

    <RelativeLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"          android:onClick="ParentLayoutClicked"         android:focusable="false"         android:orientation="horizontal" >          <Switch             android:layout_marginTop="5dip"             android:layout_marginBottom="5dip"             android:id="@+id/switch_internet"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:textOff="NOT CONNECTED"             android:textOn="CONNECTED"             android:focusable="false"             android:layout_alignParentRight="true"                                                             android:text="@string/s_internet_status" />      </RelativeLayout> 
like image 70
Aaron Avatar answered Oct 06 '22 03:10

Aaron


A better way is to prevent the Switch class from receiving MotionEvent.ACTION_MOVE events.

This can be done with:

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

Then you are free to set a click listener on the switch as appropriate.

Check out the implementation of Switch to see how dragging works. It's pretty cool!

like image 33
advait Avatar answered Oct 06 '22 04:10

advait