ButterKnife @OnClick注解在Kotlin片段中无效

9
我喜欢ButterKnife的@OnClick属性的可读性,因此即使在Kotlin中也使用它。不幸的是,当我点击时,点击处理程序并没有被触发。我有什么遗漏吗?在Kotlin中是否需要执行某些操作才能集成点击监听器? 片段:
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()
    }
}

布局

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

你可以查看生成的类。 - tynn
移除 import kotlinx.android.synthetic.main.fragment_profile.* 会有帮助吗? - EpicPandaForce
你找到解决方案了吗? - Vivek C A
我认为这是Butterknife和新的kotlin synthetic imports之间的冲突。我认为这个冲突可能已经解决了,但在我的情况下,我只是使用了Sergio的答案。 - user2836797
2个回答

5
如果您正在使用Kotlin,请将annotationProcessor替换为kapt
其原因是您可能正在使用如下依赖项:
dependencies {
  implementation 'com.jakewharton:butterknife:10.1.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
}

用以下方式替换它:

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

2
为什么不这样做?(关于IT技术方面的内容)
// 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()
}

1
但是能否直接定义一个绑定在“单击”事件上的函数呢? - Rick
实际上,在 Kotlin 中甚至不需要使用 findViewById,只需直接使用其 ID 访问视图按钮,如下所示:'btn_click_me.setOnClickListener{}' - has19
如果您添加了apply plugin: 'kotlin-android-extensions'到模块的build.gradle中,@has19已经为您提供了。 - Jose_GD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接