Search code examples
androidandroid-layoutdata-bindingandroid-adapterbutterknife

RecyclerView.ViewHolder unable to bind view with ButterKnife


I'm using ButterKnife to bind my views on my ViewHolder. My code is below:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private List<DataObject> data;

    public MyAdapter(List<DataObject> data) {
        this.data = data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);
        return new ViewHolder(view);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.row_header_view) View rowHeaderView;
        @BindView(R.id.row_header_view_text) TextView headerTextView;

        @BindView(R.id.row_data_view) View rowDataView;
        @BindView(R.id.row_data_view_text) TextView rowDataTextView;
        @BindView(R.id.row_data_view_detail_text) TextView rowDataDetailTextView;

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

For some reason in my ViewHolder all of the BindView's do nothing. They are all null. I can confirm with certainty they are in my layout. What is wrong with my above code? I have used it as per the documentation listed here:

http://jakewharton.github.io/butterknife/#reset

Is there anything else required? I'm using ButterKnife version:

compile 'com.jakewharton:butterknife:8.2.1'

If I add the below line:

rowHeaderView = view.findViewById(R.id.row_header_view);

It's able to get the view properly. But how does this make sense? Isn't ButterKnife usable where findViewById is usable?


Solution

  • Make sure that if you have use ButterKnife library to use this way

    build.gradle file of Project

    buildscript {
      repositories {
        mavenCentral()
       }
      dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
      }
    }
    

    Then, apply the 'android-apt' plugin in your module-level build.gradle and add the Butter Knife dependencies:

    apply plugin: 'android-apt'
    
    android {
      ...
    }
    
    dependencies {
      compile 'com.jakewharton:butterknife:8.2.1'
      apt 'com.jakewharton:butterknife-compiler:8.2.1'
    }