How to Build a Simple Torch App in Android using Kotlin?
Last Updated :
02 Jun, 2022
Torch Application is a very basic application that every beginner level android developer should definitely try to build while learning Android. In this article, we will be creating an application in which we will simply display a toggle button to switch on and switch off the torch.
Note: If you are looking to implement the Torch application in android using Java. Check out the following article: Torch Application in Android using Java
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--on below line we are creating a simple text view
for displaying the current status of the torch-->
<TextView
android:id="@+id/idTVTorchStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:gravity="center"
android:padding="4dp"
android:text="Torch Off"
android:textAlignment="center"
android:textColor="@color/purple_200"
android:textSize="25sp"
android:textStyle="bold" />
<!--on below line we are simply displaying a
toggle button for making torch on and off-->
<ToggleButton
android:id="@+id/idBtnSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idTVTorchStatus"
android:layout_margin="20dp"
android:backgroundTint="@color/purple_200"
android:padding="5dp"
android:textAllCaps="false"
android:textColor="@color/white"
android:textStyle="bold" />
</RelativeLayout>