Android: How to create slide (on/off) button

43,631

Solution 1

Well it seems that Switch component is the best solution if your target SDK is higher than 4.0 (Ice Cream Sandwich). So for the others who will face the same problem look at it. :)

Solution 2

//in your layout design the below line

<RelativeLayout android:layout_width="wrap_content" android:id="@+id/rl_onoff"
    android:layout_height="wrap_content">
<ImageView android:id="@+id/on_btn" android:layout_width="80dp"  android:layout_height="40dp" android:src="@drawable/on_btn" android:visibility="visible"></ImageView>
<ImageView android:id="@+id/off_btn" android:layout_width="80dp"  android:layout_height="40dp" android:src="@drawable/off_btn" android:visibility="invisible"></ImageView>
   </RelativeLayout>

// in your activity call this

ImageView mNotification_on_btn=(ImageView)findViewById(R.id.on_btn);
ImageView mNotification_off_btn=(ImageView)findViewById(R.id.off_btn);

    mNotification_on_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mNotification_on_btn.setVisibility(View.GONE);
                mNotification_off_btn.setVisibility(View.VISIBLE);
            }
        });
    mNotification_off_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mNotification_off_btn.setVisibility(View.GONE);
                mNotification_on_btn.setVisibility(View.VISIBLE);
            }
        });

// this will switch like iphone style on off toggle buttonenter image description here enter image description here

Solution 3

You can achieve this by use check box or ToggleButton. Below is an example

xml file

 <CheckBox
        android:id="@+id/check_on_of"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/chec_box_on_off"
       />

drawable chec_box_on_off file is

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/check_box_on" android:state_checked="true"/>
<item android:drawable="@drawable/check_box_off" android:state_checked="false"/>
</selector>

you will get like on off button and also you can check whether checkbox is on or off.

the java code is

 CheckBox check = (CheckBox)findViewById(R.id.check_on_of);
 check.isChecked();

Similarly, you can also achieve this using ToggleButton.

Share:
43,631
obrien
Author by

obrien

Updated on July 05, 2022

Comments

  • obrien
    obrien almost 2 years

    I'd like to create a slide button (= something as switch ) with two states: on and off so user will have to press the button and slide it to change the state (something similar as unlock slider but not cross whole screen). Do you have any idea how to do it? I really tried to find the answer but I haven't been successful.

    Thanks a lot!