Kotlin OnClick Listener

kotlin listener
android:onclick
kotlin onclicklistener recyclerview
onclicklistener android
setonclicklistener android
onclicklistener android studio
implementing onclicklistener in android
dialoginterface.onclicklistener kotlin

I am trying to get Toast from UI defined in MainActivity and writing a code in Base Activity for onClick Listener. As per requirement I had define my base class as open but still I am not getting Toast

Here is code

BaseActivity

    open class BaseActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val buttonClick= findViewById<Button>(R.id.button)
        buttonClick?.setOnClickListener {
            Toast.makeText(this@BaseActivity, "Click...", Toast.LENGTH_LONG).show()
        }

    }
}

MainActivity

    class MainActivity : BaseActivity() {

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

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"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="18dp"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:text="Hello World!"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.409" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="190dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


</android.support.constraint.ConstraintLayout>

Can you tell what wrong with code how can I get a click from it


I think the problem here is that you're calling val buttonClick= findViewById<Button>(R.id.button) in BaseActivity.onCreate, which is called in MainActivity.onCreate before you call setContentView... So the view isn't initialized yet, and you aren't subscribed for click events.

You can attach onClickListener in MainActivity, or if you still want to do it from your BaseActivity you can make additional initViews method and call it after setContentView:

class MainActivity : BaseActivity() {

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

        initViews()
    }
}



open class BaseActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    } 

    protected fun initViews() {
        val buttonClick= findViewById<Button>(R.id.button)
        buttonClick?.setOnClickListener {
            Toast.makeText(this@BaseActivity, "Click...", Toast.LENGTH_LONG).show()
        }
    }    
}

How lambdas work in Kotlin. setOnClickListener transformation , For example, the setOnClickListener function, which in Java is defined as: public void setOnClickListener(OnClickListener l) { } When we use it in Kotlin,  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.


You need to move the code of your listener in your MainActivity.

MainActivity.kt

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

            val buttonClick= findViewById<Button>(R.id.button)
            buttonClick?.setOnClickListener {
                Toast.makeText(this@MainActivity, "Click...", Toast.LENGTH_LONG).show()
            }

    }

Because you are defining your listener in your BaseActivity's onCreate your findViewById<Button>(R.id.button) is effectively null due to the fact that setContentView(R.layout.activity_main) is called after.

Android - How to achieve setOnClickListener in Kotlin?, Here is an example on how to use the onClickListener in Kotlin button1.​setOnClickListener(object : View.OnClickListener{ override fun  SetOnClickListener transformation One of the features I like most about Kotlin is that it simplifies the work with the Android framework thanks to some conventions. For example, the setOnClickListener function, which in Java is defined as: public void setOnClickListener(OnClickListener l) {


In your code, setContentView is only called after you've tried to set a listener to a nonexistent view.

One possible solution would be to only try to add the click listener (without the ?.) after you've called an abstract method that tries to set the content view.

abstract class BaseActivity: AppCompatActivity() {
    abstract val layoutId: Int

    override fun onCreate(bundle: Bundle?) {
         super.onCreate(bundle)
         setContentView(layoutId) 
         button.setOnClickListener {
            ... 

View.OnClickListener, OnClickListener. Kotlin |Java. interface OnClickListener. android.view.View.​OnClickListener. Known Direct Subclasses. CharacterPickerDialog  One question I get often is how to simplify the interaction with listeners that have several functions on Kotlin. For listeners (or any interfaces) with a single function is simple: it automatically lets you replace it by a lambda. But that’s not the case for listeners with several functions.


The thing is that you are trying to access you button in BaseActivity class, whilst your layout is loaded only inside MainActivity. Therefore the button can not be found. The solution would be:

abstract class BaseActivity : AppCompatActivity() {

   abstract val buttonClick: Button

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

       buttonClick.setOnClickListener {
           Toast.makeText(this@BaseActivity, "Click...", Toast.LENGTH_LONG).show()
    }
  }
}

class MainActivity : BaseActivity() {
   override val buttonClick: Button
        get() = button // Kotlin view binding

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

What has been done: we have defined an abstract button and assigned a click listener to it. Thus, the logic of click handling stayed in base activity, while MainActivity just defines a view (R.id.button, via kotlin view binding) to operate on.

Button on click listener example, View.OnClickListener. Kotlin |Java. public static interface View.OnClickListener. android.view.View.OnClickListener. Known indirect subclasses. Android Platform. API level 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1. Manifest.permission. Manifest.permission_group. android.accessibilityservice. AccessibilityService.MagnificationController.OnMagnificationChangedListener. AccessibilityService.SoftKeyboardController.OnShowModeChangedListener.


Use it Toast.makeText(getApplicationContext(), "Click " , Toast.LENGTH_LONG).show();

OnClickListener with function reference - Android, android kotlin - Button on click listener example. MainActivity.kt. package com.​cfsuman.kotlinexamples import android.graphics.Color import  In this video we will learn, how to set OnClickListeners for multiple buttons and handle them all in one onClick method. Instead of passing an anonymous inner class to the setOnClickListener method, we will pass the activity itself and implement the OnClickListener interface into our MainActivity.


About onclick listener - Android, I'm not sure if this is the proper place to ask, but what do you think about allowing following syntactic sugar: infix fun View.onClick( func  Ever since I created my first Android app in 2011 (it was a name generator) I have relied heavily on implementing OnClickListener to make my apps work. More recently I have been exploring different…


Android Button Using Kotlin, button' onclick in anko coroutine is deprecated now,What insteads it?


Android, android:onClick is used to define the Kotlin function to be invoked in the activity when the button is clicked. Basically, it is a click listener. android:background is