Practical No 9
<?xml version="3.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<!-- ToggleButton -->
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="ON"
android:textOff="OFF"
android:layout_centerInParent="true" />
</RelativeLayout>
Main.java
package com.example.toggle_button;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the ToggleButton
ToggleButton toggleButton = findViewById(R.id.toggleButton);
// Set a listener for the ToggleButton to detect state changes
toggleButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
// When the ToggleButton is ON
Toast.makeText(MainActivity.this, "ToggleButton ON", Toast.LENGTH_SHORT).show();
} else {
// When the ToggleButton is OFF
Toast.makeText(MainActivity.this, "ToggleButton OFF", Toast.LENGTH_SHORT).show();
}});}}