Wednesday, 12 October 2016

Switch

activitymain.xml :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  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:orientation="vertical"
  tools:context="com.kiranapp.MainActivity"
  android:background="#ddd6d6">
<Switch
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Bluetooh"
  android:layout_marginTop="30dp"
  android:id="@+id/switch1"
  android:checked="false"
  android:layout_gravity="center_horizontal" />
</LinearLayout>

MainActivity.java
:-


package com.kiranapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
  Switch aSwitch;


@Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   aSwitch=(Switch) findViewById(R.id.switch1);
  aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   if (isChecked){
   Toast.makeText(MainActivity.this,"TurnOn",Toast.LENGTH_SHORT).show();
    }
  else {
 Toast.makeText(MainActivity.this,"TurnOff",Toast.LENGTH_SHORT).show();
 }
 }
});
}
}

Output :- 


Switch
Switch fig:1




Switch
Switch fig:2

No comments:

Post a Comment