[go: up one dir, main page]

Open In App

ToggleButton in Kotlin

Last Updated : 22 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Android, the ToggleButton is just like a switch containing two states either ON or OFF which are represented using boolean values true and false respectively. ToggleButton unlike switch does not have a slider interface i.e. we cannot slide to change the states. It is just like a button. In this article, we will be discussing how to create a ToggleButton in Kotlin.

Android ToggleButton XML Attributes

Note: ToggleButton inherits the button class of android . Therefore, all the attributes of the button are also applicable here.

Following are some of the additional important attributes available along ToggleButton

Attribute Description
android:id The ID assigned to the toggle button
android:textOff The text is shown on the button when it is not checked
android:textOn The text is shown on the button when it is checked
android:disabledAlpha The alpha (opacity) to apply to the when disabled.

Create a new project in Android Studio

To create a new project in Android Studio follow these steps:

  1. Click on File, then New, and then New Project, and give a name whatever you like.
  2. Choose “Empty Activity” for the project template.
  3. Then, select Kotlin language Support and click the next button.
  4. Select minimum SDK, whatever you need

Modify activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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"
    tools:context=".MainActivity">

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Accessing the Toggle Button

The toggle button in the layout can be accessed using the findViewById() function.

val toggle: ToggleButton = findViewById(R.id.toggleButton)

After accessing set a listener to perform actions based on the toggle state using setOnCheckedChangeListener() method.

toggle.setOnCheckedChangeListener { _, isChecked -> **Perform Any Action Here**}

Modify MainActivity.kt file as mentioned below:

MainActivity.kt
package com.example.togglebuttonsample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import android.widget.ToggleButton

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toggle: ToggleButton = findViewById(R.id.toggleButton)
        toggle.setOnCheckedChangeListener { _, isChecked ->
            Toast.makeText(this, if(isChecked) "Geek Mode ON" else "Geek Mode OFF", Toast.LENGTH_SHORT).show()
        }
    }
}

Run on Emulator

Runt the Emulator

Previous Article
Next Article

Similar Reads

Dynamic ToggleButton in Kotlin
In Android, ToggleButton is just like a switch containing two states either ON or OFF which is represented using boolean values true and false respectively. ToggleButton unlike switch does not have a slider interface i.e we cannot slide to change the states. It is just like a button. In this article, we will be discussing how to create a ToggleButt
2 min read
ToggleButton in Android
ToggleButton is used to allow users to perform two operations on a single button. These are used to perform on and off operations like that of Switch. ToggleButton can perform two different operations on clicking on it. In this article, we will take a look at How to implement ToggleButton in Android. Note: This Android article covered in both Java
4 min read
Kotlin Data Types
The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects. There are different data types in Kotlin: Integer Data typeFloating-point Data
3 min read
Hello World program in Kotlin
Hello, World! is the first basic program in any programming language. Let's write the first program in Kotlin programming language. The "Hello, World!" program in Kotlin: Open your favorite editor notepad or notepad++ and create a file named firstapp.kt with the following code. // Kotlin Hello World Program fun main(args: Array<String>) { pri
2 min read
Android Shared Element Transition with Kotlin
Shared element transition is seen in most of the applications which are used when the user navigates between two screens. This type of animation is seen when a user clicks on the items present in the list and navigates to a different screen. During these transitions, the animation which is displayed is called a shared element transition. In this ar
4 min read
Kotlin | Retrieve Collection Parts
The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying the start and end indices of the sublist. The result
5 min read
Destructuring Declarations in Kotlin
Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once. For example : val (emp_id,salary) = employee These multiple variables correspond to the properties of a class that are associat
3 min read
DatePicker in Kotlin
Android DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePic
3 min read
Kotlin labelled continue
In this article, we will learn how to use continue in Kotlin. While working with a loop in the programming, sometimes, it is desirable to skip the current iteration of the loop. In that case, we can use the continue statement in the program. Basically, continue is used to repeat the loop for a specific condition. It skips the following statements a
4 min read
Expandable RecyclerView in Android with Kotlin
In this article, we will get to know how to implement the expandable RecyclerView. In General, we will show the list of items in the listview but in some situations like if you want to show the sub-list items, then we have to use an expandable list. See the below image for a better understanding. Step by Step Implementation 1. If you observe the ab
7 min read
Kotlin Exception Handling | try, catch, throw and finally
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program. There are two types of Exceptions - Checked Exceptio
6 min read
A Complete Guide to Learn Kotlin For Android App Development
Kotlin is a statically typed, cross-platform, general-purpose programming language for JVM developed by JetBrains. This is a language with type inference and fully interoperable with Java. Kotlin is concise and expressive programming as it reduces the boilerplate code. Since Google I/O 2019, Android development has been Kotlin-first. Kotlin is seam
8 min read
Kotlin if-else expression
Decision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If the condition is true then it enters into the condi
4 min read
Android - Save ArrayList to SharedPreferences with Kotlin
SharedPreferences is local storage in android which is used to store data in the form of key and value pairs within the android devices. We can store data in the form of key and value pairs using Shared Preferences. In this article, we will take a look at How to Save Array List to SharedPreferences in Android using Kotlin. A sample video is given b
9 min read
Create an Android App that Displays List of All Trending Kotlin git-hub Repositories
Kotlin is a popular programming language that has gained much attention in recent years. It is known for its simplicity, conciseness, and compatibility with existing Java code. GitHub is a popular platform for hosting and sharing code, including Kotlin projects. This article will discuss how to build an application that shows a list of Kotlin GitHu
12 min read
Kotlin Environment setup for Command Line
To set up a Kotlin environment for the command line, you need to do the following steps: Install the Java Development Kit (JDK): Kotlin runs on the Java virtual machine, so you need to have the JDK installed. You can download the latest version from the official Oracle website.Download the Kotlin compiler: You can download the latest version of the
2 min read
Kotlin Environment setup with Intellij IDEA
Kotlin is a statically typed, general-purpose programming language developed by JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011. Kotlin is object-oriented language and a better language than Java, but still be fully interoperable with Java code. Let's see how to setu
2 min read
Kotlin Nested class and Inner class
Nested Class In Kotlin, you can define a class inside another class, which is known as a nested class. Nested classes have access to the members (fields and methods) of the outer class. Here is an example of a nested class in Kotlin: C/C++ Code class Car { var make: String var model: String var year: Int inner class Engine { var horsepower: Int = 0
5 min read
Android - Line Graph View with Kotlin
Graphs are used in android applications to display vast amounts of data in an easily readable form. There are different types of graphs used such as BarGraph, GroupBar graph, point, and line graph to represent data. In this article, we will take a look at How to use Line Graph View in Android using Kotlin. A sample video is given below to get an id
3 min read
Working with Anonymous Function in Kotlin
In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kotlin compiler in most cases, for cases where it can
3 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.
2 min read
Kotlin Operators
Operators are the special symbols that perform different operation on operands. For example + and - are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. Arithmetic operatorRelation operatorAssignment operatorUnary operatorLogical operatorBitwise operator Arithmetic Operators - Op
3 min read
Kotlin Standard Input/Output
In this article, we will discuss here how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow sequence of bytes or byte streams from input device such as Keyboard to the main memory of the system and from main memory to output device such as Monitor. In Java, we use System.out.pr
5 min read
Kotlin Expression, Statement and Block
Kotlin Expression - An expression consists of variables, operators, methods calls etc that produce a single value. Like other language, Kotlin expression is building blocks of any program that are usually created to produce new value. Sometimes, it can be used to assign a value to a variable in a program. It is to be noted that an expression can co
4 min read
Kotlin for loop
In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of for loop in Kotlin: for(item in collection) { // code to execute } In Kotlin
4 min read
Kotlin while loop
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines. While loop - It consists of a block of code and a condition. First
2 min read
Kotlin do-while loop
Like Java, do-while loop is a control flow statement which executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, it totally depends upon a Boolean condition at the end of do-while block. It contrast with the while loop because while loop executes the block only when condition becomes
2 min read
Kotlin Unlabelled break
When we are working with loops and want to stop the execution of loop immediately if a certain condition is satisfied, in this case, we can use either break or return expression to exit from the loop. In this article, we will discuss learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to nea
4 min read
Kotlin labelled break
While working with loops say you want to stop the execution of loop immediately if a certain condition is satisfied. In this case you can use either break or return expression to exit from the loop. In this article, we are going to learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to neare
4 min read
three90RightbarBannerImg