Butterknife onclick 不会触发片段中的方法

Butterknife onclick does not trigger the method in a fragment

我有以下

public class InventoryFragment extends Fragment {
    @BindView(R.id.fab_fragment_inventory)FloatingActionButton mFab;
private Unbinder unbinder;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_inventory, container, false);

        unbinder = ButterKnife.bind(this, view);

return view
}

@OnClick(R.id.fab_fragment_inventory)
    public void newItemDialog(){
        // do stuff
    }

当我将方法放在 xml 上时,它会抛出此错误

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_fragment_inventory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:elevation="4dp"
android:onClick="newItemDialog"
        android:src="@drawable/vector_plus"
        app:layout_anchorGravity="bottom|right|end"/>



> java.lang.IllegalStateException: Could not find a method
> newItemDialog(View) in the activity class
> simpleinventory.simpleinventory.activities.InventoryActivity for
> onClick handler on view class
> android.support.design.widget.FloatingActionButton with id
> 'fab_fragment_inventory'

这是我的 gradle

dependencies {
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    compile 'com.android.support:cardview-v7:23.0.0'

    compile 'com.jakewharton:butterknife:8.1.0'
}

编辑 没有提到我一开始没有打开 onclick。没有它什么都不会发生。

您在 ButterKnife 中使用 onClick,它不能在 xml 文件中。所以只需从 xml 中删除 android:onClick="newItemDialog"。

编辑

您需要将此添加到 build.gradle 的第一行。

apply plugin: 'android-apt'

并且在你的项目中 build.gradle 你需要添加依赖项:

buildscript {
   repositories {
      mavenCentral()
   }

   dependencies {
      classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
   }}

你可以在github项目中看到它。

https://github.com/JakeWharton/butterknife#download