RecyclerView.ViewHolder unable to bind view with ButterKnife

KVISH picture KVISH · Jul 17, 2016 · Viewed 16.8k times · Source

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?

Answer

bastami82 picture bastami82 · Jan 2, 2017

Update for October 2016: You probably don't need apt and the android-apt plugin anymore. Version 2.2 of the Android Gradle plugin has an annotationProcessor configuration that you should be using instead.

In Android studio 2.2 onward, just add these on your build.gradle module :

compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'