Android - How to achieve setOnClickListener in Kotlin?

Viewed 215449

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

32 Answers

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 
}

Cheers!

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
        }
    }
  }
}

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()
        }
    }
}

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.

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()
    }
}

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
}

Simply you can get OnClickListener in kotlin

view1.setOnClickListener{

//body 

}

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

    tv.setOnClickListener {
       val i = Intent(this@MainActivity, SecondActivity::class.java)
       startActivity(i)
       finish()
    }

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
    }
}
    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener {
        val intent = 
    Intent(this@MainActivity,ThirdActivity::class.java)
        intent.putExtra("key", "Kotlin")
        startActivity(intent)
    }
**i have use kotlin-extension so i can access directly by button id:**


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

                    hitApiLogin()
                }
            }
        }
findViewById<Button>(R.id.signUp)?.setOnClickListener(
    Toast.makeText(mActivity, "Button Clicked", Toast.LENGTH_LONG).show()
)
   button.setOnClickListener {
          //write your code here
   }

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()
    }

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.

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
}

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 {

}

You can use setOnClickListener like this in Kotlin

button.setOnClickListener(View.OnClickListener {        
       //code
})

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") }

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
    }
}

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'
}

}

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()
            }
    
Related