Latest News

Create A Button And Handle On Click Listener In Android Studio (Kotlin)

How to create a button and handle OnClickListener in Kotlin using Android Studio?

      DESCRIPTION      

In this tutorial we will create a button and handle button click. We will display a Toast on the click of that button. However you can do your own functionality such as moving to some activity , opening fragment etc.

      VIDEO      


      SOURCE CODE      

Step 1: Create a new Project or open new project

Step 2: Code

activity_main.xml
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.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"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Click Button"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /></android.support.constraint.ConstraintLayout>

MainActivity.kt
package com.blogspot.atifsoftwares.myapplicationimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toastclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val mBtn = findViewById<Button>(R.id.btn) as ButtonmBtn.setOnClickListener {Toast.makeText(this , "Button is clicked" , Toast.LENGTH_LONG).show();}}}

Step 3: Run Project

Output
Create a button and handle on click listener in Android Studio (Kotlin)


0 Response to "Create A Button And Handle On Click Listener In Android Studio (Kotlin)"