Android - How to achieve setOnClickListener in Kotlin?

AndroidListenerKotlin

Android Problem Overview


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

Android Solutions


Solution 1 - Android

There are five 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
            }
        }
    }
}

Cheers!

Solution 2 - Android

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

Solution 3 - Android

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

Solution 4 - Android

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

Solution 5 - Android

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

Solution 6 - Android

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

Solution 7 - Android

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.

Solution 8 - Android

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

Solution 9 - Android

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
}

Solution 10 - Android

Simply you can get OnClickListener in kotlin

view1.setOnClickListener{

//body 

}

Solution 11 - Android

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

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

Solution 12 - Android

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

Solution 13 - Android

    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener {
        val intent = 
    Intent(this@MainActivity,ThirdActivity::class.java)
        intent.putExtra("key", "Kotlin")
        startActivity(intent)
    }

Solution 14 - Android

**i have use kotlin-extension so i can access directly by button id:**


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

Solution 15 - Android

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)

Solution 16 - Android

Simply do as below :

button.setOnClickListener{doSomething()}

Solution 17 - Android

findViewById<Button>(R.id.signUp)?.setOnClickListener(
    Toast.makeText(mActivity, "Button Clicked", Toast.LENGTH_LONG).show()
)

Solution 18 - Android

   button.setOnClickListener {
          //write your code here
   }

Solution 19 - Android

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

Solution 20 - Android

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.

Solution 21 - Android

You use like that onclickListener in kotlin

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {  
...
}

Solution 22 - Android

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
}

Solution 23 - Android

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 {

}

Solution 24 - Android

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
}

Solution 25 - Android

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

Solution 26 - Android

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

Solution 27 - Android

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


        }
    }

Solution 28 - Android

You can use setOnClickListener like this in Kotlin

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

Solution 29 - Android

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

Solution 30 - Android

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

Solution 31 - Android

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

}

Solution 32 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnirudh AgarwalView Question on Stackoverflow
Solution 1 - AndroidNaimatullahView Answer on Stackoverflow
Solution 2 - AndroidVinod PattanshettiView Answer on Stackoverflow
Solution 3 - AndroidAkash PatelView Answer on Stackoverflow
Solution 4 - AndroidAlf MohView Answer on Stackoverflow
Solution 5 - AndroidRonak ThakkarView Answer on Stackoverflow
Solution 6 - AndroidLuvnish MongaView Answer on Stackoverflow
Solution 7 - AndroidMallikarjun MView Answer on Stackoverflow
Solution 8 - Androidambreesh kushwahaView Answer on Stackoverflow
Solution 9 - AndroidhadilqView Answer on Stackoverflow
Solution 10 - AndroidAndroid GeekView Answer on Stackoverflow
Solution 11 - AndroidCHANDAN KUMARView Answer on Stackoverflow
Solution 12 - AndroidMaihan NijatView Answer on Stackoverflow
Solution 13 - AndroidVinay JohnView Answer on Stackoverflow
Solution 14 - Androidabhilasha YadavView Answer on Stackoverflow
Solution 15 - AndroidRedBassettView Answer on Stackoverflow
Solution 16 - AndroidKishan VView Answer on Stackoverflow
Solution 17 - Androiduser3694157View Answer on Stackoverflow
Solution 18 - AndroidResmi VenugopalView Answer on Stackoverflow
Solution 19 - AndroidSuresh B BView Answer on Stackoverflow
Solution 20 - AndroidAmit KumarView Answer on Stackoverflow
Solution 21 - AndroidShivam SharmaView Answer on Stackoverflow
Solution 22 - AndroidJosephView Answer on Stackoverflow
Solution 23 - AndroidFakhriddin AbdullaevView Answer on Stackoverflow
Solution 24 - AndroidAjay PrajapatiView Answer on Stackoverflow
Solution 25 - AndroidisijaraView Answer on Stackoverflow
Solution 26 - Androiduser2288580View Answer on Stackoverflow
Solution 27 - AndroidJyotView Answer on Stackoverflow
Solution 28 - AndroidMarium JawedView Answer on Stackoverflow
Solution 29 - AndroidFortranView Answer on Stackoverflow
Solution 30 - Androidsamuel ochubaView Answer on Stackoverflow
Solution 31 - AndroidSafal BhatiaView Answer on Stackoverflow
Solution 32 - AndroidKapsView Answer on Stackoverflow