Share
Explore

KOTLIN Android Lab 01

Here's a simple Android app using Kotlin for Android Studio Electric Eel 2022.1.1 that includes a button click and uses a view:
Here, we have created an activity called MainActivity, which extends AppCompatActivity. The onCreate() method is called when the activity is created. We set the content view to activity_main.xml using setContentView().

import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

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

val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
// Code to perform on button click
button.text = "Button Clicked"
}
}
}






We then find the button view using findViewById() and assign it to a variable called button. We set an OnClickListener to the button using setOnClickListener(). When the button is clicked, the code inside the listener is executed. Here, we simply change the text of the button to "Button Clicked".


Make sure to add a button view with id "button" in your activity_main.xml file:


<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"/>



This is a simple implementation of a button click in an Android app using Kotlin. You can modify the code to perform any desired action on button click.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.