Android ButterKnife 的使用

来源:互联网 发布:linux网络命令 编辑:程序博客网 时间:2024/06/09 20:58

绪论:本人也是刚接触ButterKnife理解不深刻。在这里只给大家介绍用法:

作用是节省大量的findViewById();可以节省大量的代码量,增加代码的可读性。

在这里是说AS的用法:

对于As的小伙伴直接操作Gradle就可以了:

添加依赖:

compile 'com.jakewharton:butterknife:8.7.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
//这一个必须要加

接下来就可以在项目中使用了,

setContentView(R.layout.activity_main);

//   ButterKnife.bind(this);这个一定要写在setContentView()之后。
     
  ButterKnife.bind(this);//this代表绑定的Activity

在Fragment中:

public class FancyFragment extends Fragment {
    @BindView(R.id.button1) Button button1;
    @BindView(R.id.button2) Button button2;


    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fancy_fragment, container, false);
        ButterKnife.bind(this, view);
        // TODO Use fields...
        return view;
    }
}

在adapter中:

public class MyAdapter extends BaseAdapter {
    @Override public View getView(int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view != null) {
            holder = (ViewHolder) view.getTag();
        } else {
            view = inflater.inflate(R.layout.whatever, parent, false);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }


        holder.name.setText("John Doe");
        // etc...


        return view;
    }


    static class ViewHolder {
        @BindView(R.id.title)
        TextView name;
        @BindView(R.id.job_title) TextView jobTitle;


        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

接下来就可以对控件操作了:

@BindView(R.id.text)
    TextView textView;

以上步骤完成之后就可以对控件做你想做的事情了!