作者:jianyue1980_852 | 来源:互联网 | 2023-09-12 14:53
Android开发中应用注入框架,可缩小findViewById的代码量,也能让咱们的代码更加整洁,有许多驰名的注入框架比方,ButterKnife,Annotation,XUti
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 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);
}
}
小伙伴们,你们当初我的项目中应用注入框架是哪一个呀?欢送在下方留言哦。