Skip to main content

android kotlin - Switch button example


Switch Button



The following kotlin tutorial will demonstrate to us how we can use a Switch button in an android application. And how we can implement the Switch button checked change listener using the kotlin programming language. We used the SwicthCompat widget in this tutorial instead the Switch/SwitchMaterial widget.




Android Developers also can use the SwitchMaterial widget instead the Switch/SwicthCompat widget. The SwitchMaterial widget used attributes from the material theme. The SwitchMaterial behaves identically to the SwitchCompat widget.




The SwicthCompat is a complete backport of the core Switch widget. The SwitchCompat widget brings the visuals and functionality of the Switch widget to older versions of the android platform. We have to put the SwicthCompat widget in our XML layout file to use it instead Switch button in an android application. We have to explicitly use the SwicthCompat widget.




Android application developers can change the Switch button thumb and track color. We can tint both the thumb and track color using API methods and XML attributes.




The Switch button OnCheckedChangeListener registers a callback to be invoked when the Switch button checked state is changed. So when users change the Switch button checked state, the developers can get the change in real time using this listener. They can perform the required action when the Switch button is checked and unchecked.




Android developers also can get the Switch button checked and unchecked state programmatically using the ‘isChecked’ property. Even the developers can change the Switch button checked state programmatically using this ‘isChecked’ property/method.




This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to see how we use a Switch/SwicthCompat button in an android application.




And how we implemented the Switch button checked change listener and how we get the Switch button checked status programmatically in an application. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.




MainActivity.kt



package com.cfsuman.kotlintutorials

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.constraintlayout.widget.ConstraintLayout


class MainActivity : AppCompatActivity() {
private lateinit var context: Context

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

// Get the context
context = this;

// Get the widgets from XML layout
val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout);
val button = findViewById<Button>(R.id.button);
val textView = findViewById<TextView>(R.id.textView);
val switchButton = findViewById<SwitchCompat>(R.id.switchButton);

// Set the layout initial background color
rootLayout.setBackgroundColor(
Color.parseColor(
if (switchButton.isChecked)"#D8BFD8" else "#F8F8F8")
)

// Set the initial status on text view
textView.text = if (switchButton.isChecked )
"Switch on" else "Switch off"

// Set an checked change listener for switch button
switchButton.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
// The switch is enabled/checked
textView.text = "Switch on"
// Change the app background color
rootLayout.setBackgroundColor(
Color.parseColor("#D8BFD8")
)
} else {
// The switch is disabled
textView.text = "Switch off"
// Set the app background color
rootLayout.setBackgroundColor(
Color.parseColor("#F8F8F8")
)
}
}

// Set a click listener for root layout object
rootLayout.setOnClickListener{
// Get the switch button state programmatically
if(switchButton.isChecked){
// If switch button is checked/on then
// The switch is enabled/checked
textView.text = "Switch is on"
}else{
// The switch is unchecked
textView.text = "Switch is off"
}
}

// Set a click listener for the button widget
button.setOnClickListener{
// Change the switch button checked state on button click
switchButton.isChecked = !switchButton.isChecked
}
}
}




activity_main.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"
android:id="@+id/rootLayout"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textSize="24sp"
android:padding="12dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Change Switch Button State"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/switchButton" />

</androidx.constraintlayout.widget.ConstraintLayout>





Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...