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);
}
}
小伙伴们,你们当初我的项目中应用注入框架是哪一个呀?欢送在下方留言哦。
感觉文章不错的,给我点个赞哇,关注一下呗!
技术交换可关注微信公众号【君伟说】,加我好友一起探讨
微信交换群:加好友 wayne214(备注技术交换)邀你入群,抱团学习共提高