What Is Toggle Button | Toggle Button In Android Example

Toggle Button – Introduction

Toggle Button –

Create activity_toggle_button 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/toggleLayout”
android:gravity=”center”
tools:context=”.toggleButton”>

<ToggleButton
android:id=”@+id/toggleButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”/>

</RelativeLayout>

Create toggleButton 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.ToggleButton;

public class toggleButton extends AppCompatActivity {

// RelativeLayout layout;
// ToggleButton toggleButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle_button);

final RelativeLayout relativeLayout = findViewById(R.id.toggleLayout); // declared the layout objects and find elements by ID
final ToggleButton toggleButton = findViewById(R.id.toggleButton); // declared the ToggleButton objects and find elements by ID

// ToggleButton Code

toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggleButton.isChecked()){
relativeLayout.setBackgroundColor(Color.BLUE);
}else {
relativeLayout.setBackgroundColor(Color.GREEN);
}
}
});

}
}

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=”.toggleButton” />
</application>

</manifest>

Toggle Button – Output

Grammarly – Best Free Grammar checker | Spelling checker | Mistake-free document writer for Laptop/Desktop
Online Surveys – Earn Real Money by Online Surveys
Kids Books – 10+ books for Kids | Age group 2 – 10 | Improve knowledge & Productivity

Leave a Reply

Your email address will not be published.