Detect switch button is ON or OFF in android dynamically

How to Show message-know when switch button is off and On in android app programmatically.

Switch button is mostly used to perform any kind of On and Off functionality inside android applications, android settings like On WiFi , Off WiFi . So here is the complete step by step tutorial for Detect switch button is ON or OFF in android dynamically.

android-project-download-code-button

How to Detect switch button is ON or OFF in android dynamically.

Code for MainActivity.java file.

package com.detectswitchbuttononoff_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;


public class MainActivity extends Activity {

 Switch switchbutton;
 TextView textview;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 switchbutton = (Switch)findViewById(R.id.switch1);
 textview = (TextView)findViewById(R.id.textView1);
 
 switchbutton.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 if(switchbutton.isChecked())
 {
 
 textview.setText("Switch Button is ON");
 
 }
 else {
 textview.setText("Switch Button is OFF");
 
 }
 
 }
 });
 
 
 }
}

Code for activity_main.xml layout file.

 <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"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.detectswitchbuttononoff_android_examples.com.MainActivity" >

 <Switch
 android:id="@+id/switch1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="Switch" />

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_above="@+id/switch1"
 android:layout_centerHorizontal="true"
 android:layout_marginBottom="74dp"
 android:text="Switch Button is OFF"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:gravity="center" />

</RelativeLayout>

Screenshots:

Detect switch button is ON or OFF in android dynamically

 

switch-off

Click here to download Detect switch button is ON or OFF in android dynamically project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *