Sunday 20 January 2013

Working with Toggle Button

Screen Shots:








1.main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:orientation="vertical" >

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="150dp"
        android:textOff="OFF"
        android:textOn="ON"
        android:textSize="20dp" />

</LinearLayout>

2.Activity:

package com.venkool.togglebutton;

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

public class ToggleButtonActivity extends Activity {
     /** Called when the activity is first created. */

     ToggleButton toggleButton;

     @Override
     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);

          // Get the Reference for ToggleButton
    toggleButton = (ToggleButton)findViewById(R.id.toggleButton);

          // set Listener for ToggleButton (CheckedListener)
    toggleButton.setOnCheckedChangeListener(new                                                       OnCheckedChangeListener() {

         public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                   // TODO Auto-generated method stub

                   if (isChecked) {
         Toast.makeText(getApplicationContext(),
                 "ToggleButton Staus ==> ON", Toast.LENGTH_LONG)
                                  .show();
                   } else {
         Toast.makeText(getApplicationContext(),
                 "ToggleButton Staus ==> OFF", Toast.LENGTH_LONG)
                                  .show();
                   }
              }
          });
     }
}

No comments:

Post a Comment