Friday, 28 August 2015

Switch in Android

activity_main.xml
-------------------
<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"

    android:id="@+id/mr"

    tools:context=".MainActivity"

    android:background="#000000">



    <Switch

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Switch"

        android:id="@+id/switch1"

        android:layout_marginTop="20dp"

        android:textSize="40dp"

        android:textColor="#ffffff"

        android:background="#99cc00"

        android:layout_gravity="center_horizontal"

        android:checked="false" />

</LinearLayout>

MainActivity.Java
-------------------
package com.android.anil.switchinandroid;



import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.CompoundButton;

import android.widget.Switch;

import android.widget.Toast;



public class MainActivity extends AppCompatActivity {

     Switch s;
  @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        s=(Switch)findViewById(R.id.switch1);

        s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

         @Override

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){

           if(buttonView.isChecked()){

              Toast.makeText(getApplicationContext(),"ON",5000).show();

            }else{

              Toast.makeText(getApplicationContext(),"OFF",5000).show();

                }

            }

        });

    }

}

Output is:
-------------
        



No comments:

Post a Comment