butterknife的使用

1.

在app/build.gradle中添加依赖 compile 'com.jakewharton:butterknife:7.0.0',然后sync。

2.

在要用到butterknife工具的activity的onCreate方法中对活动进行绑定 ButterKnife.bind(this);

3.

使用@Bind()注解来代替findviewbyid,简化了代码量,看起来也比较整洁,如下:

public class MainActivity extends BaseActivity {

  //这里要写:
   @Bind(R.id.toolbar)
    Toolbar toolbar;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //还有这一句:
        ButterKnife.bind(this);
    }

这样就省去了

XRecyclerView rv = findViewById(R.id.***);

注意:android studio 3.0之后好像会报错,如下

Annotation processors must be explicitly declared now.  The following dependencies on the compile classpath are found to contain annotation processor.  Please add them to the annotationProcessor configuration.

jetified-butterknife-7.0.0.jar (com.jakewharton:butterknife:7.0.0)
Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior.  Note that this option is deprecated and will be removed in the future.

关于注释现在必须显式声明,所以解决办法——在app目录下的build.gradle配置中,android下默认配置中加入如下代码:

android{
defaultConfig{
 ...
 //从这里开始
javaCompileOptions {
    annotationProcessorOptions {
        includeCompileClasspath true
    }
}
//从这里结束
 ...
}}

这样就可以使用该工具了。

参考链接:https://blog.csdn.net/jabony/article/details/78933963

原文地址:https://www.cnblogs.com/ksxxx/p/12123421.html