Friday, August 21, 2015

Android Switch Button Example

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="#f3f6f7"
    >
    <Switch
        android:id="@+id/sb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="On Off The Switch"
        android:layout_below="@id/sb"
        android:layout_marginTop="20dp"
        android:padding="15dp"
        android:fontFamily="sans-serif-light"
        android:textSize="25dp"
        />
</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.Switch;
import android.widget.TextView;


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
        Switch sb = (Switch) findViewById(R.id.sb);
        final TextView tv = (TextView) findViewById(R.id.tv);

        sb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    // If the switch button is on
                    tv.setBackgroundColor(Color.GREEN);
                    tv.setText("Switch is on.");
                }
                else {
                    // If the switch button is off
                    tv.setBackgroundColor(Color.RED);
                    tv.setText("Switch is off.");
                }
            }
        });
   }
}
More android examples