以前在布局中找id时,需要根据findViewById()来找;现在有了ButterKnife则可以省去一大部分时间,他是利用了依赖注入的原理,以便达到低耦合。
要使用ButterKnife,我们先要添加依赖。在build.gradle(Module:app)中添加
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
在Activity中:
在setContentView后就直接ButterKnife.bind(this).
接着就可以这样用了:
在Fragment中:
要使用Unbinder。
在onDestroy中unbind:
在点击中使用:
直接使用@Click注解,括号内填写需要为id添加的监听,方法名(我的是onTabClicked)随便取。