首页 > 代码库 > ButterKnife
ButterKnife
1、简介
ButterKnife是注解中相对简单易懂的很不错的开源框架
1.强大的View绑定和Click事件处理功能,简化代码,提升开发效率
2.方便的处理Adapter里的ViewHolder绑定问题
3.运行时不会影响APP效率,使用配置方便
4.代码清晰,可读性强
2、下载地址
https://github.com/JakeWharton/butterknife
3、使用步骤
1)在Setting->Plugins中输入butterknife添加插件
Android ButterKnife Aelezny ->点击安装
2)Module里的build.gradle里面添加
compile ‘com.jakewharton:butterknife:7.0.1‘
4、常用功能
本文主要针对7.0.1版本
1)省略findViewById()
(1)Activity中使用
以前 mTextView1 = (TextView) findViewById(R.id.butter_text_view_1);
现在
@InjectView(R.id.butter_text_view_2)
TextView mTextView2;
在设置好布局之后调用:ButterKnife.inject(this);:
注意
View变量声明的时候不能为private或者static.
(2)Fragment中使用
public class SimpleFragment extends Fragment { @InjectView(R.id.fragment_text_view) TextView mTextView; public SimpleFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_simple, container, false); ButterKnife.inject(this, view); mTextView.setText("TextView in Fragment are found!"); return view; } }
(3)Adapter ViewHolder中使用
@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.person_item_layout, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Person person = getItem(position); if (null != person) { holder.name.setText(person.getName()); } return convertView; } static class ViewHolder { @InjectView(R.id.person_name) TextView name; public ViewHolder(View view) { ButterKnife.inject(this, view); } }
2)省略setOnClickListener()
@OnClick(R.id.basic_finish_a_button) void finishA(View view) { finish(); }
ButterKnife.inject(this);
注意
注意这里方法仍然不能是private和static, 并且可以有一个参数View,也可不写.
3)ListView的点击@OnItemClick, CheckBox的@OnCheckedChanged也可以实现省略操作
4)可以一次指定多个id,为多个View绑定一个事件处理方法
@OnClick({R.id.button_enable, R.id.button_disable, R.id.button_alpha_0, R.id.button_alpha_1}) void editViewsClicked() { Toast.makeText(this, "You click the Button!", Toast.LENGTH_SHORT).show(); }
ButterKnife