Karan
Karan

Reputation: 143

Not able to use setOnClickListener on button through button id in Kotlin

I want to use setOnClickListener by the help of Button's id in Kotlin but when I try to do so I am getting an error.

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btnDatePicker.setOnClickListener { }
    }
}

XML file activity_main

<Button
        android:id="@+id/btnDatePicker"
        android:onClick="SelectDateBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/select_date"
        android:layout_marginTop="15dp"
        android:textStyle="bold"
        android:textColor="@color/grey"
        android:textSize="25sp"/>

Here I am getting error in main.kt that btnDatePicker is not defined. Please help me to resolve this.

Upvotes: 1

Views: 111

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363825

It requires the Kotlin Android Extensions.
Add the plugin in the app/build.gradle file:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

And in your class you have to add the import:

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

Also please note that the Kotlin Android Extensions is now deprecated.
You should migrate to the new library for View Binding.

In any case you can always use:

val button: Button = findViewById(R.id.btnDatePicker)

Upvotes: 2

Related Questions