Table of Contents
Switch Button – Introduction
Switch Button –
Create activity_switch File in XML
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:app=”http://schemas.android.com/apk/res-auto”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/relativeLayout1″
android:gravity=”center”
tools:context=”.switchActivity”>
<Switch
android:id=”@+id/switchButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”/>
</RelativeLayout>
Create switchActivity File in Java
package com.eiheducation.demo;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Switch;
public class switchActivity extends AppCompatActivity {
RelativeLayout relativeLayout1; // declared the layout objects
Switch switchButton; // declared the switch objects
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
// We need to find our elements by IDs
relativeLayout1 = findViewById(R.id.relativeLayout1);
switchButton = findViewById(R.id.switchButton);
// Button Code
switchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(switchButton.isChecked()){
relativeLayout1.setBackgroundColor(Color.RED);
}else {
relativeLayout1.setBackgroundColor(Color.GRAY);
}
}
});
}
}
Android Manifest File
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.eiheducation.demo”>
<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”@string/app_name”
android:roundIcon=”@mipmap/ic_launcher_round”
android:supportsRtl=”true”
android:theme=”@style/Theme.EIHeducationDemo”>
<activity
android:name=”.MainActivity”
android:label=”@string/app_name”
android:theme=”@style/Theme.EIHeducationDemo.NoActionBar”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity android:name=”.switchActivity” />
</application>
</manifest>
Switch Button – Output
Check Out the Headphones – 50% to 70% Off
Check Out the Earbuds – 50% to 70% Off
Grammarly – Best Free Grammar checker | Spelling checker | Mistake-free document writer for Laptop/Desktop
Check Out The LAB Configuration eBook – Class A, Class B, Class C, MiN worth $78 Get at $18