Android switch button example

Android switch widget is a widget which provides the functionality something similar to android toggle button. It is button which is having only two state ,ON and OFF. There is setOnCheckedChangeListener in which we can give actions whenever the state is changed.

For implementing a basic Switch button you just need to add the following code to your layout file

<Switch
android:id="@+id/switch_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:text="Swith Text" />

Now for implementing listeners to switch button you need to add the following code to your class file

Switch switch_button = (Switch) findViewById(R.id.switch_button);
//attach a listener to check for changes in state
switch_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if(isChecked){

Toast.makeText(getApplicationContext(),"Switch is ON",Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(getApplicationContext(),"Switch is OFF",Toast.LENGTH_SHORT).show();

}

}
});

Now using the following code in your class file , you can get the state of Switch at any time

if(switch_button.isChecked()){

//switch is on
}
else {

//switch is off
}

Output

android-switch-example
android-switch-example

 

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *