android-switch-button

A Switch is a two-state toggle switch widget that can select between two options. The user may drag the “thumb” back and forth to choose the selected option, or simply tap to toggle as if it were a checkbox.




Follow me on Instagram

Android Screen Layout


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:padding="5dp"
tools:context=".MainActivity" >

<Switch
android:id=”@+id/mySwitch”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
android:layout_marginLeft=”48dp”
android:layout_marginTop=”26dp”
android:height=”50dp”
android:text=”@string/switch_text”
android:textSize=”20sp”
android:switchMinWidth=”50sp”
android:switchPadding=”50sp”/>
</RelativeLayout>

Android Main Activity

package com.panayiotisgeorgiou.switchbuttonexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends Activity {

private Switch mySwitch;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mySwitch = (Switch) findViewById(R.id.mySwitch);

// set the switch to ON
mySwitch.setChecked(true);
// attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

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

if (isChecked) {

Toast.makeText(getApplicationContext(), “The switch is ON”,
Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(getApplicationContext(),
“The switch is OFF”, Toast.LENGTH_SHORT).show();
}

}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

References

Android Reference

Follow me on Twitter


Follow me on Github

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Instagram.