Skip to main content

Command Palette

Search for a command to run...

Basic Interactivity UI in Kotlin

Published
1 min read
Basic Interactivity UI in Kotlin
J

Love to Build Fully Functional Apps and Websites

in Linear Layout ! Create 2 Buttons in in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/dark"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20.dp"
        android:text="Dark theme" />

    <Button
        android:id="@+id/light"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Light Theme" />
</LinearLayout>

and In MainActivity ! Define the button Variablers and we can change the color on click ! (setBackgroundResource) is the in Build function helps in changing the background

// Changing Themes using Buttons !

val buttonDark = findViewById<Button>(R.id.dark)
val buttonLight = findViewById<Button>(R.id.light)
val layout = findView


Bash


setBackgroundResourceById<LinearLayout>(R.id.main)

buttonDark.setOnClickListener {
    layout.setBackgroundResource(R.color.black)
}

buttonLight.setOnClickListener {
    layout.setBackgroundResource(R.color.white)
}