Friday, 28 August 2015

ToggleButton 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:id="@+id/myid"

    android:orientation="vertical"

    tools:context=".MainActivity">





    <ToggleButton

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="New ToggleButton"

        android:id="@+id/toggleButton"

        android:layout_marginTop="25dp"

        android:layout_gravity="center_horizontal" />

</LinearLayout>


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



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.Toast;

import android.widget.ToggleButton;



public class MainActivity extends AppCompatActivity {

   ToggleButton tb;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        tb=(ToggleButton)findViewById(R.id.toggleButton);

       tb.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