Looking For Anything Specific?

[Tutorial] How to setOnClickListener in Android Button Click with Kotlin

Hello dear reader / Developers,

In this post, we are going to learn about how to set setOnClickListener to a button in android with kotlin. So, in general, a button in android is a user interface that provides a variety of user interaction, and to give a beautiful UI, also there will be at least one button in the android application which the user will interact to complete an action such as login or make a toast message like how we did in the previous tutorial how to show toast message in android fragment with kotlin, or and in most cases, buttons are used to navigate to another screen like after we login we go to, let's say the profile screen or dashboard of an application. You want to learn how to navigate from one fragment to another follow the below link to learn about android kotlin, An in case if you're wondering how to setoncheckedchangelistener to an android checkbox checkout here [Tutorial] How to Use Checkbox in Android Kotlin With Sample Code Github

You might be interested:
So let's start by adding a button click event to our layout, for most of the time, we are going to use the android constraint layout because which is a pretty good and advance layout and reduces the complex nesting of multiple layouts, you can learn about the basics of constraint layout here, then we can add a button to our constraint layout then we can set an onClickListener to it with kotlin.

<Button    
android:id="@+id/startActivityButton"    
android:layout_width="wrap_content"    
android:layout_height="wrap_content"    
android:layout_marginTop="32dp"    
android:background="@color/colorAccent"    
android:padding="16dp"    
android:text="Start Second Activity"    
android:textAllCaps="false"    
android:textColor="#FFF"    
app:layout_constraintEnd_toEndOf="parent"    
app:layout_constraintStart_toStartOf="parent"    
app:layout_constraintTop_toBottomOf="@+id/textView2" />

Above is the simple code to add a button to the constraint layout in android, later we are going to use this button in our activity to add a click listener, which will trigger the button click event in your application. This button was in an Activity file so now we are going to get the button reference in the activity file. Later in this tutorial, we will learn how to add a setOnClickListener to a button in fragment in android kotlin.

kotlin findviewbyid in button



How to Declare a Button in Kotlin Android 

So now head to the activity file and get the button reference using the findViewById method. By calling findViewById method we must pass a valid R.id reference of a widget or layout or any component we want to access from our XML file.  This method is a type-specific method, which means you have to define which data type it is going to access like Button, TextView or EditText, etc. In kotlin, you can write the findViewById method in two types,

private lateinit var startActivityButton: Button

startActivityButton = findViewById(R.id.startActivityButton)

or

val startActivityButton = findViewById<Button>(R.id.startActivityButton)

These are the ways you can write a findViewById in kotlin, the difference here is defining the type before and after, so in the first case if we add the type at the declaration, like this startActivityButton = findViewById<Button>(R.id.startActivityButton) it will show a warning as "Remove explicit type argument ".

But instead, if we give the type parameter as TextView it will show an error "Required Button. Found TextView!" that's because we have already given the type as Button so it will not compile until you change one of the types to match other or not to give the type-token

You Might Have Missed:


Also in the second case if we skip the type-token it will throw an error "Type inference failed ..." which is because the method didn't know about the type of the variable, And in here if you type the type variable as TextView it will not throw an error like above, instead it will let you compile but it will throw a run time exception as cannot cast Button as TextView or like so if we try to do like giving the type as TextView in findViewById method. so be sure about the data types.

Now that we have got the reference to the button we can add a click listener to it in kotlin,

Button click event in kotlin android

Below is the classic way of writing the setOnClickListener to a button in android, well this code might look just like java because yes it is more of Java, that's because I wanted our fellow java readers also to understand the code

startActivityButton.setOnClickListener(object : View.OnClickListener {
    override fun onClick(v: View?) {
        //Do your action here    }
})

What we did in the above code is simple, we called the setOnClickListener function in the Button, and we implement the onClick method from View.OnClickListener, as Kotlin doesn't have a new keyword, we are using object keyword to write the click listener, so inside we override the onClick method, which will be called once the button is clicked by the user. We can add some action to start a new activity.

Let's rewrite the code a little bit, which might look like this,

startActivityButton.setOnClickListener{    
          //Your action     
}

So, what we did in here is we simplified the code by introducing lambda function, with this we can reduce some lines, both the codes are going to give the same result, but the number of lines in here is reduced by lambda functions. Which is a good thing right?. So by introducing the lambda function, we can get rid of the interface implementation and method overriding.

Now you may ask how to change the button when you click the button, like changing the button's text to "clicked" when clicking ?. In the lambda function, if the overridden function has only one parameter we can use the "it" keyword to access the variable, if there is more than one like in a dialog interface we can name the parameters, you can as name the only parameter also if that's the case then use "->" after defining the parameters name to access it internally refer the below code.

startActivityButton.setOnClickListener{view->    
view.apply {         
this as Button
        text = "Button Clicked"        
 }
//do your thing   
}

Here we have renamed our first parameter as "view" because it will only make sense, yeah I know it is a button. And here we are using one more Kotlin feature which is a scope function apply. With that, we typecast the view as Button and change the text = "Button Clicked", by this

change button text onclick in android


We have successfully added a click listener on the android button in kotlin from activity now we can do the same from the fragment. In our previous tutorial, we have discussed how to add fragment in android with kotlin and how to navigate from fragment to fragment in a post, read that here.

Once we added our fragment we can get the reference of our button click event using findViewById, but wait we can't use that method inside a fragment so we have to get the method from a view, so now get the reference from the view which is being returned from the fragment and the rest is same to implement an on-click listener in a button with kotlin, below is a sample code

val rootView = inflater.inflate(R.layout.fragment_toast, container, false)
showToastButton = rootView.findViewById(R.id.showToastButton)

showToastButton.setOnClickListener{    Toast.makeText(requireContext(),"Showing fragment......",Toast.LENGTH_SHORT).show()
}

This is how you need to get the reference of a Button or TextView inside a fragment...

You can get the complete code below:
GDrive Link: ButtonExampleByMADTutorial

Thanks for reading.

!!!Spread The Word!!!

keywords:
button click event in kotlin android
button onclicklistener in android kotlin
kotlin findviewbyid onclick
tutorial kotlin setonclicklistener button android
Tutorial on how to use button click on android using kotlin
how setonclicklistener button android
setonclicklistener button android in kotilin