Use the following snippet to add a Switch to your layout via XML:
<Switch
android:id="@+id/on_off_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="OFF"
android:textOn="ON"/>
Then in your Activity's onCreate method, get a reference to your Switch and set its OnCheckedChangeListener:
Switch onOffSwitch = (Switch) findViewById(R.id.on_off_switch);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.v("Switch State=", ""+isChecked);
}
});