当前位置: 代码迷 >> 综合 >> Android Butterknife 注解框架的使用
  详细解决方案

Android Butterknife 注解框架的使用

热度:40   发布时间:2024-01-10 21:29:30.0

Android Butterknife 注解框架的使用方法

ButterKnife是一个专注于Android系统的View注入框架,可以减少大量的findViewById以及OnClickListener,以及绑定资源到类成员上可以使用@BindBool、@BindColor、@BindDimen、@BindDrawable、@BindInt、@BindString。使用时对应的注解需要传入对应的id资源,例如@BindString你需要传入R.string.id_string的字符串的资源id

ButterKnife优势

1、强大的View绑定和Click事件处理功能,简化代码,提升开发效率
2、方便的处理Adapter里的ViewHolder绑定问题
3、运行时不会影响APP效率,使用配置方便
4、代码清晰,可读性强


如何添加ButterKnife相关依赖

在项目的project 的build.gredle 文件中的dependencies标签下添加。
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
   buildscript {repositories {jcenter()}dependencies {classpath 'com.android.tools.build:gradle:2.2.2'classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files}
}
allprojects {repositories {jcenter()}
}
task clean(type: Delete) {delete rootProject.buildDir
}
在module的build.gredle 文件中添加
apply plugin: 'android-apt'
在module的build.gredle 文件中的dependencies标签中添加
 compile 'com.jakewharton:butterknife:8.4.0'apt 'com.jakewharton:butterknife-         compiler:8.4.0'
   apply plugin: 'com.android.application'
apply plugin: 'android-apt'
android {compileSdkVersion 23buildToolsVersion "23.0.1"aaptOptions.cruncherEnabled = falseaaptOptions.useNewCruncher = falsedefaultConfig {applicationId "com.scott.o2o"minSdkVersion 17targetSdkVersion 23versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}
}dependencies {compile fileTree(include: ['*.jar'], dir: 'libs')androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {exclude group: 'com.android.support', module: 'support-annotations'})testCompile 'junit:junit:4.12'compile 'com.jakewharton:butterknife:8.4.0'apt 'com.jakewharton:butterknife-compiler:8.4.0'}

如何使用

  • Activity 中控件ID 注解: @BindView()

    代码示例:

  public class GoodsFeedbackActivity extends BaseActivity{private Activity activity;//注册id@BindView(R.id.feedback_content_edt)EditText contentEdt;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_goods_feedback);//初始化ButterKnife.bind(this);activity = this;initView();}private void initView(){registerBack();setTitle("快速反馈");//使用String str = contentEdt.getText().toString();} }
  • fragment 中控件ID注解: @BindView()
    @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {view = inflater.inflate(R.layout.fragment_car, null);activity = getActivity();ButterKnife.bind(activity,view);return view;}
  • @BindString() :绑定string 字符串
 public class GoodsFeedbackActivity extends BaseActivity{private Activity activity;@BindView(R.id.feedback_submit_btn)Button btn;@BindString( R.string.app_name) //绑定string 字符串String msg;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_goods_feedback);//初始化ButterKnife.bind(this);activity = this;initView();}private void initView(){registerBack();setTitle("快速反馈");btn.setText(msg);}
  • @BindArray() : 绑定string里面array数组
 public class GoodsFeedbackActivity extends BaseActivity{private Activity activity;@BindView(R.id.feedback_submit_btn)Button btn;@BindArray(R.array.strCity)String [] strArr;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_goods_feedback);//初始化ButterKnife.bind(this);activity = this;initView();}/**<string-array name="strCity"><item >北京</item><item >上海</item><item >广州</item><item >深圳</item></string-array>*/private void initView(){registerBack();setTitle("快速反馈");btn.setText(strArr[0]);} }
  • @BindColor( ) : 绑定一个颜色值
 public class GoodsFeedbackActivity extends BaseActivity{private Activity activity;@BindView(R.id.feedback_submit_btn)Button btn;@BindColor(R.color.orange)int color;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_goods_feedback);//初始化ButterKnife.bind(this);activity = this;initView();}private void initView(){registerBack();setTitle("快速反馈");btn.setTextColor(color);}}
  • @OnClick( ) : 绑定控件点击事件
    @OnLongClick( ) : 绑定控件长按事件
    public class GoodsFeedbackActivity extends BaseActivity{private Activity activity;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_goods_feedback);//初始化ButterKnife.bind(this);activity = this;initView();}private void initView(){registerBack();setTitle("快速反馈");}@OnClick(R.id.feedback_submit_btn) //给 button1 设置一个点击事件public void showToast(){Toast.makeText(this, "is a click", Toast.LENGTH_SHORT).show();}@OnLongClick(R.id.feedback_submit_btn) //给 button1 设置一个长按事件public boolean showToast2(){Toast.makeText(this, "is a long click", Toast.LENGTH_SHORT).show();return true ;} }

Android studio Butterknife插件的安装与使用

Butterknife 安装

点击导航栏File选择Settings..然后按照下图的顺序依次操作进行安装,由于我的已安装过了所以显示的是Uninstall,未安装显示的是Inststall plugin绿色按钮。
如下图:

Android studio Butterknife插件使用

安装完成插件后,会提示重启AS,重启完后,可以写一个布局并且新建一个代码类测试下。测试的过程中要注意的是,需要将光标移到setContentView(R.layout.feedback_submit_btn),将光标放到R.layout.feedback_submit_btn,然后右键Generate就有了。要注意一定要将光标放在R.layout.feedback_submit_btn上面。

如下图:

补充

Fragment的生命周期不同于Activity,当Butterknife在onCreateView上进行绑定时,需要再onDestroyView上进行解绑,Butterknife.bind()方法提供了一个Unbinder 返回值,在onDestroyView上调用相关的unbinder方法即可

private Unbinder unbinder; 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fancy_fragment, container,false); unbinder = ButterKnife.bind(this, view); 
return view; 
}@Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); 
}}
  相关解决方案