Android ButterKnife

2019-03-06 00:26发布

问题:

I've installed ButterKnife my build.gradle looks like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.jakewharton:butterknife:8.4.0'
}

My loginActivity looks like this:

package com.example.egen.forum;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        Toast.makeText(getApplicationContext(), "Your toast message.",
                Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.btnLogin) public void test() {
        Toast.makeText(getApplicationContext(), "Your toast message.",
                Toast.LENGTH_SHORT).show();
    }
}

The second toast does not show up. What am I doing wrong here?

回答1:

You haven't included annotation processor for ButterKnife code generation. Do it like described on the GitHub page:

dependencies {
  compile 'com.jakewharton:butterknife:8.4.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}

And apply the plugin:

apply plugin: 'com.jakewharton.butterknife'

Otherwise, your code looks fine.

Explanation: ButterKnife library uses annotation processor for generating the code that provides the references to views and executes ButterKnife annotated methods. If you rebuild your project, and the AndroidStudio shows that the @OnClick annotated method is unused, then somethings wrong. If the annotation processor is provided and works correctly, it should show as used and lead to a generated method.



回答2:

Add this line:

annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

as well in your build.gradle.

See here for more info



回答3:

Well, Butterknife is yesterday, use databinding instead: https://developer.android.com/topic/libraries/data-binding/index.html. This is almost the same tool out of the box