Saturday, August 22, 2015

How to add listener for a ToggleButton in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#ccd4cd"
    >
    <ToggleButton
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ToggleButton;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        ToggleButton toggle = (ToggleButton) findViewById(R.id.toggle);

        // Set a checked change listener for toggle button
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    // if toggle button is enabled/on
                    rl.setBackgroundColor(Color.parseColor("#FF63D486"));

                    // Make a toast to display toggle button status
                    Toast.makeText(getApplicationContext(),
                            "Toggle is on", Toast.LENGTH_SHORT).show();
                }
                else{
                    // If toggle button is disabled/off
                    rl.setBackgroundColor(Color.parseColor("#FFD4558C"));

                    // Make a toast to display toggle button status
                    Toast.makeText(getApplicationContext(),
                            "Toggle is off", Toast.LENGTH_SHORT).show();
                }
            }
        });
  }
}


More android examples