ButterKnife 注解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ButterKnife 注解相关的知识,希望对你有一定的参考价值。
简介
依赖:【compile ‘com.jakewharton:butterknife:8.0.1‘ 】注意:7.0版本与8.0版本方法名有所改动,整体业务逻辑和原理没什么变动在android编程过程中,我们会写大量的布局和点击事件,像初始view、设置view监听这样简单而重复的操作让人觉得麻烦类,所以可以采用注解的方式去实现,而ButterKnife则是注解中相对简单易懂的很不错的开源框架,而网上的文档和例子都过时了,7.0之后的版本改动很大,之前的注解都不能用了,所以借鉴官方文档总结了一下,接下来就介绍一下如何使用。基本参照官方文档,加上自己的心得。ButterKnife 优势:
- 1.强大的View绑定和Click事件处理功能,简化代码,提升开发效率
- 2.方便的处理Adapter里的ViewHolder绑定问题
- 3.运行时不会影响APP效率,使用配置方便
- 4.代码清晰,可读性强
使用心得:
- 1.Activity中ButterKnife.bind(this);必须在setContentView();之后,且父类bind绑定后,子类不需要再bind
- 2.Fragment中ButterKnife.bind(this, mRootView);
- 3.属性布局不能用private or static 修饰,否则会报错
- 4.setContentView()不能通过注解实现。
Zelezny插件的使用在AndroidStudio->File->Settings->Plugins->搜索【Zelezny】下载添加就行,可以快速生成对应组件的实例对象,不用手动写。使用时,在要导入注解的Activity 或 Fragment 或 ViewHolder的layout资源代码上,右键——>Generate——Generate ButterKnife Injections,然后就出现如下图的选择框。
常用功能
1、绑定Activity或Fragment,父类中绑定后子类不需要再绑定public class SimpleFragment extends Fragment {@BindView(R.id.fragment_text_view) TextView mTextView;private Unbinder unbinder;public SimpleFragment() {}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_simple, container, false);unbinder = ButterKnife.bind(this, view);//绑定Activity为ButterKnife.bind(this);mTextView.setText("TextView in Fragment are found!");return view;}@Overridepublic void onDestroyView() {unbinder.unbind();//解除绑定,官方文档只对fragment做了解绑super.onDestroyView();}}2、绑定资源@BindView(R.id.app_name) TextView mAppNameTextView;//view@BindString(R.string.app_name) String appName;//sting@BindColor(R.color.red) int textColor;//颜色@BindDrawable(R.mipmap.ic_launcher) Drawable drawable;//drawble@BindDrawable(R.drawable.selector_image) Drawable selector;3、点击事件的绑定
- a.直接绑定一个方法
@OnClick(R.id.submit)public void submit(View view) { }
- b.所有监听方法的参数是可选的
@OnClick(R.id.submit)public void submit() { }
- c.定义一个特定类型,它将自动被转换
@OnClick(R.id.submit)public void sayHi(Button button) { }
- d.多个view统一处理同一个点击事件,很方便,避免抽方法重复调用的麻烦
@OnClick({ R.id.door1, R.id.door2, R.id.door3 })public void pickDoor(DoorView door) { }
- e.自定义view可以绑定自己的监听,不指定id
public class FancyButton extends Button {@OnClickpublic void onClick() { }}
- f.给EditText加addTextChangedListener(即添加多回调方法的监听的使用方法),利用指定回调,实现想回调的方法即可,哪个注解不会用点进去看下源码上的注释就会用了
@OnTextChanged(value = R.id.mobileEditText, callback = OnTextChanged.Callback.BEFORE_TEXT_CHANGED)void beforeTextChanged(CharSequence s, int start, int count, int after) { }@OnTextChanged(value = R.id.mobileEditText, callback = OnTextChanged.Callback.TEXT_CHANGED)void onTextChanged(CharSequence s, int start, int before, int count) { }@OnTextChanged(value = R.id.mobileEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)void afterTextChanged(Editable s) { }4、Adapter的ViewHolder 绑定static class ViewHolder {@Bind(R.id.hello_world)TextView textview;public ViewHolder(View view) {ButterKnife.bind(this, view);}}5、对一组View进行统一操作
- a.装入一个list
@Bind({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews;
- b.设置统一处理
static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {@Override public void apply(View view, int index) {view.setEnabled(false);}};static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {@Override public void set(View view, Boolean value, int index) {view.setEnabled(value);}};
- c.统一操作处理,例如设置是否可点,属性等
ButterKnife.apply(nameViews, DISABLE);ButterKnife.apply(nameViews, ENABLED, false);6、可选绑定:默认情况下,“绑定”和“监听”绑定都是必需的。如果不能找到目标视图,则将抛出异常。所以做空处理@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere;@Nullable @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() { }7、代码混淆-keep class butterknife.** { *; }-dontwarn butterknife.internal.**-keep class **$$ViewBinder { *; }-keepclasseswithmembernames class * {@butterknife.* <fields>;}-keepclasseswithmembernames class * {@butterknife.* <methods>;}
Activity
public class SimpleActivity extends AppCompatActivity {@BindView(R.id.simple_activity_text_view) TextView mTextView; //this field should not be declared private or static@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_simple);ButterKnife.bind(this);// ButterKnife.inject(this) should be called after setContentView()mTextView.setText("View视图的绑定");}@OnClick(R.id.simple_activity_button)void onButtonClick(View view) { //the method should not be declared private or static//you can write the parameter (View view) as above or just write onButtonClick() leave parameters empty, both are okToast.makeText(this, "事件绑定", Toast.LENGTH_SHORT).show();}//bind event to CheckBox@OnCheckedChanged(R.id.simple_activity_checkbox)void onCheckedChanged(CompoundButton button, boolean checked) {Toast.makeText(this, "CheckBox状态改变了:" + checked, Toast.LENGTH_SHORT).show();}}
Fragment
public class SimpleFragmentActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_simple_fragment);}}<fragment xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/fragment"android:name="com.example.mengdd.butterknifesample.SimpleFragment"android:layout_width="match_parent"android:layout_height="match_parent" />public class SimpleFragment extends Fragment {@BindView(R.id.fragment_text_view) TextView mTextView;private Unbinder unbinder;public SimpleFragment() {}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_simple, container, false);unbinder = ButterKnife.bind(this, view);mTextView.setText("TextView in Fragment are found!");return view;}@Overridepublic void onDestroyView() {unbinder.unbind();super.onDestroyView();}}
ListView
public class ListViewActivity extends AppCompatActivity {@BindView(R.id.my_list_view) ListView mListView;private PersonAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_list_view);ButterKnife.bind(this);adapter = new PersonAdapter(this, MockDataUtils.getPersons());mListView.setAdapter(adapter);}@OnItemClick(R.id.my_list_view)void onItemClick(int position) {//though there are 4 parameters, you can just write the one you want to useToast.makeText(this, "点击事件: " + adapter.getItem(position).getName(), Toast.LENGTH_SHORT).show();}@OnItemLongClick(R.id.my_list_view)boolean onItmeLongClick(int position) {Toast.makeText(this, "长点击事件:" + adapter.getItem(position).getName(), Toast.LENGTH_SHORT).show();if (position % 2 == 0) return true;else return false; //if return false, the onItemClick() will be invoked反射调用 when touch up}}
Adapter
public class PersonAdapter extends BaseAdapter {private LayoutInflater mInflater;private List<Person> data;public PersonAdapter(Context context, List<Person> data) {this.mInflater = LayoutInflater.from(context);this.data = data;}@Overridepublic int getCount() {int count = 0;if (null != data) count = data.size();return count;}@Overridepublic Person getItem(int position) {Person person = null;if (null != data) person = data.get(position);return person;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic 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());holder.age.setText(String.valueOf(person.getAge()));holder.location.setText(person.getLocation());holder.work.setText(person.getWork());}return convertView;}static class ViewHolder {@BindView(R.id.person_name) TextView name;@BindView(R.id.person_age) TextView age;@BindView(R.id.person_location) TextView location;@BindView(R.id.person_work) TextView work;public ViewHolder(View view) {ButterKnife.bind(this, view);}}}
Spinner
public class SpinnerActivity extends AppCompatActivity {@BindView(R.id.my_spinner) Spinner mSpinner;private ArrayAdapter<CharSequence> adapter;private List<CharSequence> items;private String[] strings;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_spinner);ButterKnife.bind(this);strings = getResources().getStringArray(R.array.planets_array);items = new ArrayList<CharSequence>(Arrays.asList(strings));adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, items);adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);mSpinner.setAdapter(adapter);}@OnClick(R.id.clear_spinner_data)void clearSpinnerData() {adapter.clear();}@OnClick(R.id.set_spinner_data)void setSpinnerData() {items = new ArrayList<CharSequence>(Arrays.asList(strings));adapter.addAll(items);}@OnItemSelected(R.id.my_spinner)void onItemSelected(int position) {//默认回调OnItemSelected.Callback.ITEM_SELECTEDToast.makeText(this, "position: " + position, Toast.LENGTH_SHORT).show();}@OnItemSelected(value = R.id.my_spinner, callback = OnItemSelected.Callback.NOTHING_SELECTED)void onNothingSelected() {Toast.makeText(this, "神马都没有", Toast.LENGTH_SHORT).show();}}
View集合
public class ViewListActivity extends AppCompatActivity {@BindViews({R.id.label_first_name, R.id.label_middle_name, R.id.label_last_name}) List<TextView> labelViews;@BindViews({R.id.first_name, R.id.middle_name, R.id.last_name}) List<EditText> nameViews;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_view_list);ButterKnife.bind(this);}@OnClick(R.id.button_disable)void disableEditViews() {ButterKnife.apply(nameViews, DISABLE);}@OnClick(R.id.button_enable)void enableEditViews() {ButterKnife.apply(nameViews, ENABLED, true);}@OnClick(R.id.button_alpha_0)void labelAlphaTo0() {//PropertyButterKnife.apply(labelViews, View.ALPHA, 0f);}@OnClick(R.id.button_alpha_1)void labelAlphaTo1() {ButterKnife.apply(labelViews, View.ALPHA, 1f);}//Actionstatic final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {@Overridepublic void apply(View view, int index) {view.setEnabled(false);}};//Setterstatic final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {@Overridepublic void set(View view, Boolean value, int index) {view.setEnabled(value);}};//you can bind listener to multiple views@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();}}
!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--WizRtf2Html>!--more-->
以上是关于ButterKnife 注解的主要内容,如果未能解决你的问题,请参考以下文章
Android 注解框架 Butterknife的核心代码分析笔记
Android 注解框架 Butterknife的核心代码分析笔记