Basic Interactivity UI in Kotlin

1 min read

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)
}
0
Subscribe to my newsletter
Read articles from Jubair Ahmed directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Jubair Ahmed
Jubair Ahmed
Love to Build Fully Functional Apps and Websites