Detailed usage of ButterKnife for Android

I believe that many Android developers are tired of findViewById(), which is basically repetitive operations, so we can use the dependency injection framework to be lazy. At present, the two most used are probably ButterKnife and dagger, which are translated into butter knife and dagger in English, and the names are very cool.

Today we will introduce the usage of ButterKnife in detail

ButterKnife is a dependency injection framework open sourced by Square's Android god Jake Wharton, a useful butter knife.

GitHub address

## Add dependencies * First in Module's build.gradle
dependencies {
  compile 'com.jakewharton:butterknife:8.5.1'
  annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}

Add to the first line of build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.butterknife'
  • In the project's build.gradle
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
}

Use in Activiy

@Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    mUnbinder = ButterKnife.bind(this);
    // TODO Use fields...
  }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

First call `ButterKnife.bind(this)` in the onCreate method to get an `Unbinder` object, and then call the `unbind()` method in the `onDestroy` method to unbind.

* Bind View

@BindView(R.id.tv_title)
View mTitleTv;
  • Of course, it can also bind multiple views at once
@BindViews({ R.id.image_first, R.id.image_second, R.id.image_third})
List<ImageView> mImageViews;
  • ButterKnifeIt also provides some concise methods for manipulating the view
// apply方法会自动遍历传入的数组和集合,将所有imageviw透明度设为50%
ButterKnife.apply(mImageViews, View.ALPHA, 0.5f);

  • In addition, we can also customize the operation of the view:
// 代码无实际意义,只是为了演示。
ButterKnife.apply(mImageViews, new ButterKnife.Action<ImageView>() {
         @Override
         public void apply(@NonNull ImageView view, int index) {
                view.setVisibility(View.GONE);
         }
});

Here index is the subscript, or index, of each ImageView.

  • Binding resources
@BindString(R.string.title)
String title;

@BindDrawable(R.drawable.graphic)
Drawable graphic

@BindColor(R.color.red)
int redColor;

Remember that none of these member variables can be preceded by a private modifier.

  • Binding listener event

Monitoring of a single view

 @OnClick(R.id.btn_back})
        public void onClick(View view) {
           // do sth
 }

Monitoring of multiple Views

    @OnClick({R.id.tv_finish, R.id.btn_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_finish:
                // do sth
                break;
            case R.id.btn_back:
                // do sth
                break;
        }
    }
其他如onFocusChange、OnItemSelected等都与onClick事件类似,读者可自行实验。

We can see that after using ButterKnife, we no longer need to findViewById, nor set view.setOnClickListener one by one, is it very convenient? Let's introduce its usage in fragment

Use in Fragment

  • initialization
 @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view= inflater.inflate(getLayoutResId(), container, false);
        mUnbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }

In the fragment, except for some differences in the binding and unbinding methods, other usages are exactly the same as in the activity.

used in the 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);
    }
  }
}

Used in custom view (no need to specify id)

public class FancyButton extends Button {
    
    
  @OnClick
  public void onClick() {
    // TODO do something!
  }
}

All the usages of ButterKnife are introduced here. It can reduce our repeated findView operations and make the code elegant and concise. I feel that ButterKnife is particularly powerful.

Guess you like

Origin blog.csdn.net/Leavessilent/article/details/60872096