Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 856
obrien Avatar asked Nov 16 '11 11:11

obrien


People also ask

What is the slider button on Android?

The Switch is another type of toggle button that came into effect since Android 4.0 which provides a slider control. Starting with ToggleButton, we turned to switch, and now, from Android Support Library v21, we have a new style called SwitchCompat that we are going to use in our app.

Which control can be used for on off state for a button?

In Android, Switch is a two-state toggle switch widget that can select between two options. It is used to display checked and unchecked state of a button providing slider control to user. Switch is a subclass of CompoundButton. It is basically an off/on button which indicate the current state of Switch.


1 Answers

//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 hereenter image description here

like image 139
Padma Kumar Avatar answered Oct 08 '22 00:10

Padma Kumar