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

obrien picture obrien · Nov 16, 2011 · Viewed 43k times · Source

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!

Answer

Padma Kumar picture Padma Kumar · Nov 16, 2011

//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