Thursday, 22 January 2015

Switch Example

switch example in android.
  We require API level 14





activity_main.xml

<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"
    tools:context=".MainActivity" >

    <Switch
        android:id="@+id/main_switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="27dp"
        android:layout_marginTop="46dp"
        android:text="Switch" />

</RelativeLayout>

      
MainActivity.java



package com.example.switch2;

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

public class MainActivity extends Activity  {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              final Switch switch1=(Switch)findViewById(R.id.main_switch1);
              switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                          
       @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                          
    boolean on=switch1.isChecked();
                    
if(on) {
Toast.makeText(getApplicationContext(), "Switch is on..", Toast.LENGTH_LONG).show();
  }
else  {
Toast.makeText (getApplicationContext(), "Switch is off..",Toast.LENGTH_LONG).show();
                           }
                    
                     }
              });
       }

}

}

No comments:

Post a Comment