butterknife简介及Generate ButterKnife Injections 不出现的问题解决

1、概述

butterknife是一款as的功能强大插件。有了它,你几乎能够和findViewById说byebye了。javascript

2、使用

github地址:https://github.com/avast/android-butterknife-zeleznyhtml

3、问题解决

Generate ButterKnife Injections 不出现的问题解决

一、下载后重启须重启as,方生效java

二、打开Gradle App,添加 compile 'com.jakewharton:butterknife:7.0.1'依赖android

三、请务必将鼠标光标悬停在R.layout.xxx处,点击右键!请详细参阅https://github.com/avast/android-butterknife-zeleznygit

 

 

 

ButterKnife基本使用

Butter Knife处理字段和方法绑定.
 
重要更新: 目前(2016.4.29), ButterKnife的最新版本是8.0.1.
如下原文是针对ButterKnife v6.1.0的, v8.0.1主要的不一样在如下几个关键词:
复制代码
@InjectView -> @BindView
@InjectViews -> @BindViews
ButterKnife.inject(this) -> ButterKnife.bind(this)


ButterKnife.reset(this) ->  

private Unbinder unbinder; 
unbinder = ButterKnife.bind(this, view); 
@Override
public void onDestroyView() {
    unbinder.unbind();
    super.onDestroyView();
}
复制代码

 

 

配置:

用gradle配置的时候加入:
compile 'com.jakewharton:butterknife:6.1.0'
注意是加在Module: app的gradle文件中.
加上以后不用运行什么命令,直接Sync一下就能够在External Libraries里面看到butterknife.
 

功能1: 不再用写findViewById()啦.

之前的:
mTextView1 = (TextView) findViewById(R.id.butter_text_view_1);
如今能够这样实现:
首先在变量声明的时候加上注解:
@InjectView(R.id.butter_text_view_2)
TextView mTextView2;
若是id找不到,会在编译的时候报错.
 
以后在设置好布局以后调用ButterKnife.inject():
复制代码
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo_butter_knife);
 
    //using butter knife
    ButterKnife.inject(this);
}
复制代码
以后View对象就能够直接使用了.
 
须要注意的是View变量声明的时候不能为 private或者static.
除了Activity以外,你能够提供其余的View Root,来获取对象(执行注入).
还能够用来简化Adapter里面的ViewHolder:
 

ButterKnife in Fragment

在Fragment中也可使用ButterKnife来获取View:
复制代码
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;
    }
}
复制代码

 

ButterKnife in Adapter ViewHolder
Adapter有一种经常使用的优化策略,就是使用ViewHolder来减小findViewById()的重复调用.
之前写过相关的博文:  http://www.cnblogs.com/mengdd/p/3254323.html
 
用了ButterKnife以后, 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());
            holder.age.setText(String.valueOf(person.getAge()));
            holder.location.setText(person.getLocation());
            holder.work.setText(person.getWork());
        }
 
        return convertView;
    }
 
    static class ViewHolder {
        @InjectView(R.id.person_name)
        TextView name;
        @InjectView(R.id.person_age)
        TextView age;
        @InjectView(R.id.person_location)
        TextView location;
        @InjectView(R.id.person_work)
        TextView work;
 
        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
复制代码
能够看到ViewHolder类加了一个带参数View的构造方法,用注解标记每一个字段,不再须要在 getView()方法里调用findViewById()方法了.
  

功能2: 不再用写setOnClickListener()啦.

好比以前的:
复制代码
    finishButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
复制代码
如今能够写成:
    @OnClick(R.id.basic_finish_a_button)
    void finishA(View view) {
        finish();
    }
注意这里方法仍然不能是 private和static, 而且能够有一个参数View,也可不写.
全部listener的参数都是optional的,能够写,也能够不写.
而且写的时候能够直接写一个具体的子类,好比参数View能够写成Button,这里的cast是自动完成的.
 
注意仍是须要调用一下 ButterKnife.inject(this);
不然事件绑定不成功.
忘记调用ButterKnife.inject(this);对于findView来讲会报错,可是对于绑定事件来讲不会报错,只是没有事情发生.
 
除了点击事件@OnClick,还有ListView的点击 @OnItemClick, CheckBox的@OnCheckedChanged等等.
能够一次指定多个id,为多个View绑定一个事件处理方法,好比:
//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();
} 
 

功能3: 组建View List: 把多个View放在一块儿用

能够同时获取多个View,放在一个List中:
@InjectViews({R.id.label_first_name, R.id.label_middle_name, R.id.label_last_name})
List<TextView> labelViews;

@InjectViews({R.id.first_name, R.id.middle_name, R.id.last_name})
List<EditText> nameViews; 
注意id用逗号分隔,大括号包围,外面才是小括号.
 
apply()方法容许你为一组对象批量地设置值.
apply()方法共有3种形式:
public static <T extends View> void apply(List<T> list, Action<? super T> action)
public static <T extends View, V> void apply(List<T> list, Setter<? super T, V> setter, V value)
public static <T extends View, V> void apply(List<T> list, Property<? super T, V> setter, V value)
即Action, Setter和Property三种.
其中Action和Setter都是ButterKnife的类,须要继承,写本身的子类实现,而后传入对象.
Setter的第三个参数能够指定要set到什么值.
 
 
具体的使用能够参见例子:
 
 

其余实用方法

1.注入重置(Injection Rest):

能够用 reset()方法将ButterKnife注入的View引用设置为null.
好比在Fragment的onCreateView()里调用ButterKnife.inject()方法注入了一些View,在 onDestroyView()里想把它们置为null,能够直接调用ButterKnife.reset(this);方法.
 

2.选择性注入(Optional Injection): 

默认状况下,@InjectView和listener的注入都是必须的,若是target view没有被发现,则会报错.
为了抑制这种行为,能够用 @Optional注解来标记field和方法,让注入变成选择性的,若是targetView存在,则注入, 不存在,则什么事情都不作.
当布局被复用时,这个@Optional注解颇有用.
 

3.多方法的listener(Multi-method Listeners):

有一些View的listener是有多个回调方法的,好比Spinner的onItemSelectedListener:
复制代码
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    }
 
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});
复制代码

 

方法注解能够用来绑定到这些方法中的任何一个.
每个注解有一个默认的callback,指定它绑定到什么方法上;能够经过callback参数指定为一个特定的方法.
好比:
没有指定callback,默认对应onItemSelected()方法:
@OnItemSelected(R.id.my_spinner)
    //default callback : ITEM_SELECTED
void onItemSelected(int position) {
    Toast.makeText(this, "position: " + position, Toast.LENGTH_SHORT).show();
}
 
指定了callback,对应onNothingSelected()方法:
@OnItemSelected(value = R.id.my_spinner, callback = OnItemSelected.Callback.NOTHING_SELECTED)
void onNothingSelected() {
    Toast.makeText(this, "Nothing", Toast.LENGTH_SHORT).show();
}
 
注意的是Spinner中只要有数据,默认都会选中第0个数据,因此想进入到onNothingSelected()方法,就须要把Adapter中的数据都清空.
具体完整例子见:

4.findById()方法

ButterKnife.findById()能够用来获取Activity,Dialog或View中的任何View.
ButterKnife自动完成了类型转换,因此获取出来之后不用进行显式强转,直接赋值给具体的View类型引用便可.
 
 

Resources:

Sample Project:
 
相关文章
相关标签/搜索