2017-10-21 157 views
0

我喜歡ButterKnife的@OnClick屬性的可讀性:因此,我甚至在Kotlin中使用它。不幸的是,點擊時點擊處理程序不會被解僱。我錯過了什麼嗎?有什麼我需要做的事情來將click listener集成到kotlin中嗎?ButterKnife @OnClick註釋不能在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

你可以看看生成的類。 – tynn

+0

是否除去'import kotlinx.android.synthetic.main.fragment_profile。*'help? – EpicPandaForce

回答

0

你爲什麼不去做這樣的嗎?

// 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([email protected], "You clicked me.", Toast.LENGTH_SHORT).show() 
} 
+0

但是可以直接定義一個函數來綁定點擊嗎? – Rick