Butterknife onclick不会在片段中触发该方法

时间:2016-06-27 02:04:49

标签: android android-fragments butterknife

我有以下

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'

这是我的傻瓜

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。没有它没有任何反应。

1 个答案:

答案 0 :(得分:1)

您正在使用onClick与ButterKnife,它不能在xml文件中。所以只需删除android:onClick =&#34; newItemDialog&#34;来自xml。

修改

您需要在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