Android:使用ButterKnife总结
Android:使用ButterKnife总结
-
简介:
在Android开发过程中,经常会用到findViewById,在使用一些点击事件时就要用到setOnClickListener。而ButterKnife的功能就是可以大量节省这些步骤(可视化一键生成),提高代码的可读性,使逻辑更加清晰。
-
使用
第一步:
去github查看官方的引用教程:https://github.com/JakeWharton/butterknife
第二步:
安装插件:在File->Setting->Plugins中输入 ButterKnife Zelezny
重启AS即可。
举例:
1.app/build.gradle
apply plugin: 'com.android.application' apply plugin: 'com.jakewharton.butterknife' android { compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.note.tianheng.cp.first_butterknife" minSdkVersion 15 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' implementation 'com.jakewharton:butterknife:10.2.1' annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1' }
2.build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.5.1' classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
3.点击”Sync Now”同步一下就就可以配置完成。
4.在布局中设置控件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:text="Name" /> </LinearLayout>
5.将光标移动到R.layout.layout_main(光标一定要移到),使用快捷键alt+insert,会弹出如下窗口,选择Generate Butterknife Injections(就是最后一项)
继而,会出现如下窗口:
从窗口中可以看见有Element(控件类型)、ID(就是控件在xml文件中的ID)、OnClick(点击事件,将其勾选会自动帮我们完成点击事件的定义)、Variable Name(变量名,可以自己修改),左下角的Create ViewHolder勾选后会帮我们构造ViewHolder类(可以自己尝试一下,反正ctrl+z就可以返回上一步)。这里,我是在勾选Button的OnClick后直接点击Confirm。
public class MainActivity extends AppCompatActivity { @BindView(R.id.button) Button mButton; @BindView(R.id.button2) Button mButton2; @BindView(R.id.button3) Button mButton3; @BindView(R.id.button4) Button mButton4; @BindView(R.id.editText) EditText mEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); ButterKnife.bind(this); } @OnClick({R.id.button, R.id.button2, R.id.button3, R.id.button4}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.button: break; case R.id.button2: break; case R.id.button3: break; case R.id.button4: break; } } }
可以看到,已经自动帮我们把控件找到,并对勾选了OnClick的控件添加了点击事件。
绑定注解,视图,资源,等等,一共13个
名称 | 解析 |
---|---|
@BindViews | 绑定多个view id 为一个view的list变量 @BindViews({ R.id.*, R.id.*, R.id.* }) List<EditText> nameViews; |
@BindView | 绑定一个view id为一个view变量@BindView(R.id.*) TextView title; |
@BindArray | 绑定String中的array数组 @BindArray(R.array.*)String[] citys; |
@BindBitmap | 绑定图片资源文件, @BindBitmap(R.mipmap.*) Bitmap bitmap; |
@BindBool | 绑定真假boolean @BindBool(R.bool.*) |
@BindColor | 绑定颜色 @BindColor(R.color.*) |
@BindDimen | 绑定尺寸 @BindDimen(R.dimen.*) Float spacer; |
@BindDrawable | 绑定Drawable @BindDrawable(R.drawable.*) Drawable graphic |
@BindFloat | 绑定Float |
@BindInt | 绑定Int |
@BindString | 绑定一个String id为String变量, @BindString(R.string.app_name) String msg |
@BindAnim | 绑定动画 |
@BindFont | 绑定字体文字 |
绑定事件,一共有12个事件监听
名称 | 解析 |
---|---|
@OnClick | 点击事件 |
@OnCheckedChanged | 选中,选中取消 |
@OnEditorAction | 软键盘的功能键 |
@OnFocusChange | 焦点改变 |
@OnItemClick | Item被点击事件(注意这里有坑,如果item里面有Button等这些有点击的控件事件的,需要设置这些控件属性focusable为false) |
@OnItemLongClick | Item长按,返回真则可以拦截onItemClick |
@OnItemSelected | Item被选择事件 |
@OnLongClick | 长按事件 |
@OnPageChange | 页面改变事件 |
@OnTextChanged | EditText的文本改变事件 |
@OnTouch | 触摸事件 |
@Optional | 选择性注入,如果当前对象不存在,就会抛出一个异常,为了压制这个异常,可以在变量或者方法上加入一**解,让注入变成选择性的,如果目标View存在,则注入, 不存在,则什么事情都不做 |
注意事项
1、在Activity 类中绑定 :ButterKnife.bind(this);必须在setContentView();之后绑定;且父类bind绑定后,子类不需要再bind。
2、在非Activity 类(eg:Fragment、ViewHold)中绑定: ButterKnife.bind(this,view);这里的this不能替换成getActivity()。
3、在Activity中不需要做解绑操作,在Fragment 中必须在onDestroyView()中做解绑操作。
4、使用ButterKnife修饰的方法和控件,不能用private or static 修饰,否则会报错。错误: @BindView fields must not be private or static. (com.xxxxx.button)
5、setContentView()不能通过注解实现。(其他的有些注解框架可以)
6、使用Activity为根视图绑定任意对象时,如果你使用类似MVC的设计模式你可以在Activity 调用ButterKnife.bind(this, activity),来绑定Controller。
7、使用ButterKnife.bind(this,view)绑定一个view的子节点字段。如果你在子View的布局里或者自定义view的构造方法里 使用了inflate,你可以立刻调用此方法。或者,从XML inflate来的自定义view类型可以在onFinishInflate回调方法中使用它。