9

I like the readability of the @OnClick attribute from ButterKnife: hence, I'm using it even in Kotlin. Unfortunately, the click handler just isn't being fired when I click. Am I missing something? Is there something I have to do to integrate the click listener in kotlin?

Fragment:

import kotlinx.android.synthetic.main.fragment_profile.*

class ProfileFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val view = inflater!!.inflate(R.layout.fragment_profile, container, false)
        ButterKnife.bind(this, view)


        return view
    }

    companion object {
        fun newInstance(): ProfileFragment {
            return ProfileFragment()
        }
    }

    @OnClick(R.id.fab)
    public fun onFab() {
        Toast.makeText(activity, "ABC", Toast.LENGTH_LONG).show()
        Snackbar.make(container, "Hey there!", Snackbar.LENGTH_LONG).show()
    }
}

Layout

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="300dp">

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:layout_gravity="bottom|right|end"
    android:src="@drawable/ic_edit"
    app:fabSize="normal"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp"/>

</android.support.design.widget.CoordinatorLayout>

2 Answers2

5

If you are using Kotlin, replace annotationProcessor with kapt

The reason behind it is that may be you are using dependencies like this :

dependencies {
  implementation 'com.jakewharton:butterknife:10.1.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
}

replace it like this:

dependencies {
  implementation 'com.jakewharton:butterknife:10.1.0'
  kapt'com.jakewharton:butterknife-compiler:10.1.0'
}
Rishabh Saxena
  • 1,765
  • 15
  • 26
2

Why don't you do it like this?

// get reference to button
val btn_click_me = findViewById(R.id.btn_click_me) as Button
// set on-click listener
btn_click_me.setOnClickListener {
    // your code to perform when the user clicks on the button
    Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
}
Sergio
  • 844
  • 2
  • 9
  • 26
  • 1
    But can a function be defined directly which binds to on click? – Rick Dec 05 '17 at 06:32
  • actually u don't need to even use findViewById in kotlin , just access the view button directly using its id like this 'btn_click_me.setOnClickListener{}' – has19 Apr 17 '19 at 22:26
  • @has19 provided you added `apply plugin: 'kotlin-android-extensions'` to the module's build.gradle – Jose_GD Aug 28 '20 at 15:25