我喜欢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>
答案 0 :(得分:2)
你为什么不这样做?
// 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 :(得分:1)
如果您使用的是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'
}