177

I wanted to know that how we set basic onClickListener in Kotlin for Android Development.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Anirudh Agarwal
  • 2,044
  • 2
  • 14
  • 8
  • 6
    It's probably popular because Android Studio converts the Java to `button.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View) { /*do work*/} })` and then provides an advisory on their generated code that we should convert it to a lambda. – Joe Lapp May 28 '19 at 20:46
  • 12
    Kotlin is damn unintuitive. No idea why Google is investing so much in it – Mehdi Haghgoo Jul 12 '19 at 18:24
  • 6
    Why everyone is posting same answer with a slight difference? The answer is simple `view.setOnClickListener { ... }`. Seems like everyone is so eager to earn reputation. – Aziz Aug 21 '19 at 13:42
  • @MehdiHaghgoo Bruh – imashnake_ Aug 12 '22 at 03:34
  • @iamshnake ....?! – Mehdi Haghgoo Aug 12 '22 at 05:16
  • @MehdiHaghgoo I think it's mostly to get away from things like NullPointerException, which happens a lot in Java, from what I understand. With Kotlin, it looks like we traded that for a number of ways to do the same thing. I speak from experience when I say that can be overwhelming for a newbie. – N.Barrett Oct 18 '22 at 02:41
  • @N.Barrett agreed. I even call the !! operator in Kotlin the "Leave-me-alone operator". – Mehdi Haghgoo Oct 25 '22 at 20:10

32 Answers32

182

There are six ways to use SetOnClickListener:

First:

button.setOnClickListener {
    // Do some work here
}

Second:

button.setOnClickListener(object : View.OnClickListener {
    override fun onClick(view: View?) {
        // Do some work here
    }

})

Third:

button.setOnClickListener(View.OnClickListener { view ->
    // Do some work here
})

Fourth:

class MainActivity : AppCompatActivity(), View.OnClickListener{
   
    lateinit var button : Button
            
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.button1)
        button.setOnClickListener(this)
    }
        
    override fun onClick(view: View?) {
        when(view?.id){
            R.id.button1->{
                // do some work here
            }
        }
    }
}

Fifth:

class MainActivity : AppCompatActivity(){

    lateinit var button : Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.button1)
        button.setOnClickListener(listener)
    }
    
    val listener= View.OnClickListener { view ->
        when (view.getId()) {
            R.id.button1 -> {
                // Do some work here
            }
        }
    }
}

Sixth

button.setOnClickListener { view ->         
    // Do some work here 
}
starball
  • 20,030
  • 7
  • 43
  • 238
Naimatullah
  • 3,749
  • 2
  • 13
  • 12
85

Suppose you have textView to click

text_view.text = "Hello Kotlin";

text_view.setOnClickListener {
    val intent = Intent(this@MainActivity, SecondActivity::class.java)
    intent.putExtra("key", "Kotlin")
    startActivity(intent)
}
Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148
Vinod Pattanshetti
  • 2,465
  • 3
  • 22
  • 36
  • 3
    Oh yeah! Type inference takes care off all the messy bits. Thanks! – Joe Lapp May 28 '19 at 20:47
  • 1
    Can someone point me to this way of calling methods with Functional Interface args in Kotlin? Normally in Java, I'd just do textView.SetOnClickListener(view -> { doSomething() }); – Anjil Dhamala Jun 22 '21 at 15:01
59

Use below code

val textview = findViewById<TextView>(R.id.textview)
textview.setOnClickListener(clickListener)

val button = findViewById<Button>(R.id.button)
button.setOnClickListener(clickListener)

clickListener code.

val clickListener = View.OnClickListener {view ->

    when (view.getId()) {
        R.id.textview -> firstFun()
        R.id.button -> secondFun()
    }
}
Akash Patel
  • 2,757
  • 1
  • 22
  • 30
35

Here is an example on how to use the onClickListener in Kotlin

button1.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {
                //Your code here
            }})
Dima Kozhevin
  • 3,602
  • 9
  • 39
  • 52
Alf Moh
  • 7,159
  • 5
  • 41
  • 50
32

Method 1:

txtNext.setOnClickListener {
        //Code statements
    }

Method 2:

class FirstActivity : AppCompatActivity(), View.OnClickListener {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_first)
    txtNext.setOnClickListener(this)
}

override fun onClick(v: View) {
    when (v.id) {
        R.id.txtNext -> {
            //Code statements
        }
        else -> {
            // else condition
        }
    }
  }
}
Ronak Thakkar
  • 2,515
  • 6
  • 31
  • 45
14

For using multiple ids:

textview1.setOnClickListener(clickListener)
textview2.setOnClickListener(clickListener)

Create anonymous class:

 private val clickListener: View.OnClickListener = View.OnClickListener { view ->
    when (view.id) {
        R.id.textview1-> { 
           Toast.makeText(this, "Clicked 1", Toast.LENGTH_SHORT).show()
        }
        R.id.textview2-> { 
           Toast.makeText(this, "Clicked 2", Toast.LENGTH_SHORT).show()
        }
    }
}
Luvnish Monga
  • 7,072
  • 3
  • 23
  • 30
8

First you have to get the reference to the View (say Button, TextView, etc.) and set an OnClickListener to the reference using setOnClickListener() method

// get reference to button
val btn_click_me = findViewById(R.id.btn_click_me) as Button
// set on-click listener
btn_click_me.setOnClickListener {
    Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
}

Refer Kotlin SetOnClickListener Example for complete Kotlin Android Example where a button is present in an activity and OnclickListener is applied to the button. When you click on the button, the code inside SetOnClickListener block is executed.

Update

Now you can reference the button directly with its id by including the following import statement in Class file. Documentation.

import kotlinx.android.synthetic.main.activity_main.*

and then for the button

btn_click_me.setOnClickListener {
    // statements to run when button is clicked
}

Refer Android Studio Tutorial.

arjun
  • 1,645
  • 1
  • 19
  • 19
6

Use this code to add onClickListener in Kotlin

val button : Button = getView()?.findViewById<Button>(R.id.testButton) as Button
button.setOnClickListener {view ->
         Toast.makeText(context, "Write your message here", Toast.LENGTH_LONG).show()
    }
}
MichaelStoddart
  • 5,571
  • 4
  • 27
  • 49
6

I see a lot of suggestions here, but this collection is missing the following.

button.setOnClickListener(::onButtonClicked)

and in the current class we have a method like this:

private fun onButtonClicked(view: View) {
     // do stuff
}
hadilq
  • 1,023
  • 11
  • 25
5

Simply you can get OnClickListener in kotlin

view1.setOnClickListener{

//body 

}
Android Geek
  • 596
  • 8
  • 14
5

var tv = findViewById(R.id.tv) as TextView

    tv.setOnClickListener {
       val i = Intent(this@MainActivity, SecondActivity::class.java)
       startActivity(i)
       finish()
    }
Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
CHANDAN KUMAR
  • 99
  • 1
  • 1
  • please use this one very easy(set id, click listener and navigate one class to another class) – CHANDAN KUMAR Jun 20 '18 at 06:42
  • Welcome to Stack Overflow! Please don't just throw your source code here. Be nice and try to give a nice description to your answer, so that others will like it and upvote it. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – sɐunıɔןɐqɐp Jun 20 '18 at 07:12
4

A simple way would be to register a click listener and create a click listener with a lambda expression.

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

    // click listener registered
    myButton.setOnClickListener(clickListener)
}

And implement the clickListener:

private val clickListener: View.OnClickListener = View.OnClickListener { _ ->
    // do something here
}

You can replace _ with a name if you need the view to use it. For example, you need to check the id of click listener.

private val clickListener: View.OnClickListener = View.OnClickListener { view ->
    if(view.id == login.id) {
        // do something here
    }
}
Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
4
    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener {
        val intent = 
    Intent(this@MainActivity,ThirdActivity::class.java)
        intent.putExtra("key", "Kotlin")
        startActivity(intent)
    }
Vinay John
  • 990
  • 12
  • 13
3
**i have use kotlin-extension so i can access directly by button id:**


btnSignIN.setOnClickListener {
            if (AppUtils.isNetworkAvailable(activity as BaseActivity)) {
                if (checkValidation()) {

                    hitApiLogin()
                }
            }
        }
abhilasha Yadav
  • 217
  • 1
  • 9
2

There are several different ways to achieve this, as shown by the variety of answers on this question.

To actually assign the listener to the view, you use the same methods as you would in Java:

button.setOnClickListener()

However, Kotlin makes it easy to assign a lambda as a listener:

button.onSetClickListener {
    // Listener code
}

Alternatively, if you want to use this listener for multiple views, consider a lambda expression (a lambda assigned to a variable/value for reference):

val buttonClickListener = View.OnClickListener { view ->
    // Listener code
}

button.setOnClickListener(buttonClickListener)
another_button.setOnClickListener(buttonClickListener)
RedBassett
  • 3,469
  • 3
  • 32
  • 56
2

Simply do as below :

button.setOnClickListener{doSomething()}

ADM
  • 20,406
  • 11
  • 52
  • 83
Kishan V
  • 41
  • 8
2
findViewById<Button>(R.id.signUp)?.setOnClickListener(
    Toast.makeText(mActivity, "Button Clicked", Toast.LENGTH_LONG).show()
)
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
2
   button.setOnClickListener {
          //write your code here
   }
2

Button OnClickListener implementation from function in android using kotlin.

Very First Create Button View From .xml File

             `<Button
                android:id="@+id/btn2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Button2"
                android:layout_weight="0.5"/>`

//and create button instance in Activity

 private var btn1:Button?=null

or

//For Late Initialization can Follow like this,

private lateinit var btn1:Button

//in onCreate,

 btn1=findViewById(R.id.btn1) as Button

     btn1?.setOnClickListener { btn1Click() }

//implementing button OnClick event from Function,

 private fun btn1Click() {
        Toast.makeText(this, "button1", Toast.LENGTH_LONG).show()
    }
Suresh B B
  • 1,387
  • 11
  • 13
2

You can use view.setOnClickListener{ // your task to execute }

Kotlin type inference and automatic lambda expression will handle the boilerplate. Note: Here view can be anything like TextView or button etc.

Amit Kumar
  • 21
  • 4
1

You use like that onclickListener in kotlin

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {  
...
}
Shivam Sharma
  • 290
  • 2
  • 14
1

First find the button, to prevent the cast from the View you can use the <> as follows :

val button = findViewById<Button>(R.id.button);

Once you have an instance of the Button, you can now attach the click listener as follows :

button.setOnClickListener {  
 // You code here
}
Derlin
  • 9,572
  • 2
  • 32
  • 53
Joseph
  • 5,793
  • 4
  • 34
  • 41
1

Here's the solution. Your code will like this:

button.setOnClickListener {
            //your code here
        }

No need to add anything. like below:

val button = findViewById<Button>(R.id.Button)
button.setOnClickListener {

}
Fakhriddin Abdullaev
  • 4,169
  • 2
  • 35
  • 37
0
val saveButton:Button = findViewById(R.id.button_save)

saveButton.setOnClickListener{
// write code for click event
}

with view object
saveButton.setOnClickListener{
view -> // write code for click event
}
Ajay Prajapati
  • 668
  • 1
  • 10
  • 18
0

The easiest way that I know to achieve that is through Kotlin Android Extensions.

On your app/build.gradle

apply plugin: 'kotlin-android-extensions'

If your button is called 'btnAdd', then on your fragment or activity import the following:

import kotlinx.android.synthetic.main.fragment_transactions.btnAdd

 override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    btnAdd.setOnClickListener {
        Toast.makeText(context , "Done", 10).show()
    }
}
isijara
  • 155
  • 2
  • 9
0

If you want to simulate the old anonymous way in Kotlin I found this worked perfectly.

 btnNewWay!!.setOnClickListener(object:View.OnClickListener {
    override fun onClick(v: View?) {
        //Your Code Here!
    }})
user2288580
  • 2,210
  • 23
  • 16
0

Add clickListener on button like this

    btUpdate.setOnClickListener(onclickListener)

add this code in your activity

 val onclickListener: View.OnClickListener = View.OnClickListener { view ->
        when (view.id) {
            R.id.btUpdate -> updateData()


        }
    }
Jyot
  • 540
  • 5
  • 17
0

You can use setOnClickListener like this in Kotlin

button.setOnClickListener(View.OnClickListener {        
       //code
})
Marium Jawed
  • 391
  • 4
  • 9
0

Add in build.gradle module file

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

For Activity add

private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}

Add on click

binding.button.setOnClickListener { Log.d("TAG", "Example") }
Fortran
  • 2,218
  • 2
  • 27
  • 33
0

In case anyone else wants to achieve this while using binding. If the id of your view is button_save then this code can be written, taking advantage of the kotlin apply syntax

binding.apply {
    button_save.setOnClickListener {
        //dosomething
    }
}

Take note binding is the name of the binding instance created for an xml file . Full code is below if you are writing the code in fragment. Activity works similarly

private lateinit var binding: FragmentProfileBinding

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    binding = FragmentProfileBinding.inflate(inflater, container, false)
 
    return binding.root
}

// onActivityCreated is deprecated in fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.apply {
    button_save.setOnClickListener {
        //dosomething
    }
}
Reza
  • 906
  • 2
  • 15
  • 29
samuel ochuba
  • 67
  • 1
  • 10
0

Best for achieve click listener in Kotlin(Mean Without findview by id you can click or intalize the textview, button, spinner etc)

Step: -

  1. Go to your Build/gradle
  2. Add this line : - id 'kotlin-android-extensions'
  3. Then Sync the project.

This is Gradle File plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-android-extensions' }

android { compileSdkVersion 30 buildToolsVersion "30.0.3"

defaultConfig {
    applicationId "com.safal.myapp"
    minSdkVersion 21
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
    jvmTarget = '1.8'
}

}

Safal Bhatia
  • 245
  • 2
  • 6
0

There are multiple ways to do it, I would prefer kotlin way of doing it and minimise the boilerplate code.

Say you have a Button defined in your layout file like this,

<Button
    android:id="@+id/clickMe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Ok"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

and you want to add onClickListener to this button clickMe You would need below to do this,

  1. Add kotlin extension to your existing plugins in build.gradle file like below and sync

         plugins {
            id 'kotlin-android-extensions'
        }
    
  2. Add the listener like this,

        clickMe.setOnClickListener {
                Toast.makeText(this@MainActivity, "You clicked me!", Toast.LENGTH_SHORT).show()
            }
    
Kaps
  • 2,345
  • 2
  • 26
  • 37
  • Do note that Kotlin synthetics (i.e. the `kotlin-android-extensions` plugin used here) has been _deprecated_ since [November 2020](https://android-developers.googleblog.com/2020/11/the-future-of-kotlin-android-extensions.html) and will be planned for **removal** in [Kotlin 1.8, which is slated to be "released end 2022"](https://android-developers.googleblog.com/2022/02/discontinuing-kotlin-synthetics-for-views.html). The suggested alternative would be to use [View Binding](https://developer.android.com/topic/libraries/view-binding). (See also https://stackoverflow.com/q/65179275) – Edric Mar 21 '22 at 15:58