Android开发中使用注入框架,可减少findViewById的代码量,也能让我们的代码更加整洁,有许多著名的注入框架比如,ButterKnife,Annotation,XUtils,afinal等,最开始接触的是XUtils,后面开始接触到了ButterKnife; XUtils包含了许多模块,比如数据库操作orm,网络请求,图片及视图注入,而如果仅需要做视图注入的话BK更合适些。
今天来看看ButterKnife的使用。
@[toc]
1.添加依赖
在项目的app/build.gradle文件中,添加如下代码
android {
...
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.jakewharton:butterknife:10.2.2'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.2'
}
当前的开发环境:Android Studio: 3.1.2,直接使用官网上的的依赖版本会报错:
Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:7:5-62:19 to override.
应该是AndroidX的问题, 同时在Issues中,作者也做了回答
You cannot use 10.x.x unless you also migrated to AndroidX. If you haven't migrated, you'll need to stick to 9.0.0 for now. Once you migrate, then you can update to 10.1.0 (or whatever is latest at that time).
As mentioned in the change log, 10.0.0 only supports AndroidX-enabled projects. If you have not yet migrated to AndroidX you need to use 9.0.0 for now.
因为我目前的项目没有migrated to AndroidX,所以会报错,修改一下butterknife的版本就可以了,将上面的依赖修改为如下
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
然后点击Sync Now,重新build一下项目就好了
2.使用
使用@BindView取代findViewById
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.pieImageView) PieImageView pieImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
pieImageView.setProgress(50);
}
}
@OnClick点击事件
@OnClick(R.id.pieImageView) void click() {
Toast.makeText(this, "单击了吗?", Toast.LENGTH_SHORT).show();
}
资源绑定
class ExampleActivity extends Activity {
@BindString(R.string.title) String title;
@BindDrawable(R.drawable.graphic) Drawable graphic;
@BindColor(R.color.red) int red; // int or ColorStateList field
@BindDimen(R.dimen.spacer) float spacer; // int (for pixel size) or float (for exact value) field
// ...
}
列表Adapter的ViewHolder
static class ViewHolder {
@BindView(R.id.title) TextView name;
@BindView(R.id.job_title) TextView jobTitle;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
小伙伴们,你们现在项目中使用注入框架是哪一个呀?欢迎在下方留言哦。