How to add click listener event on Switch button to get its value in android dynamically.
In this tutorial we are adding setOnCheckedChangeListener() method on switch button which help us to retrieve switch button value by passing isChecked argument inside it. So here is the complete step by step tutorial for Add/Set setOnCheckedChangeListener to switch button in android.
How to Add/Set setOnCheckedChangeListener to switch button in android.
Code for MainActivity.java file.
package com.setoncheckedchangelistenerswitch_android_examples.com; import android.app.Activity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.TextView; public class MainActivity extends Activity { Switch button; TextView textview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textview = (TextView)findViewById(R.id.textView1); button = (Switch)findViewById(R.id.switch1); button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(isChecked) { textview.setText("Switch ON"); } else { textview.setText("Switch 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.setoncheckedchangelistenerswitch_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" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/switch1" android:layout_below="@+id/switch1" android:layout_marginTop="45dp" android:text="Switch OFF" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
Screenshots: