如何替代Butterknife的@BindView?求RecyclerView.ViewHolder手写实现
Hey there! I see you're moving away from ButterKnife to vanilla Android code, and you're having inconsistent results when using findViewById instead of @BindView. Let's break down what's missing and fix this step by step.
The Key Mistake to Watch For
ButterKnife automatically handles binding views to the itemView of your RecyclerView.ViewHolder. When you switch to manual findViewById, you can't just call findViewById directly — you need to call it on the itemView passed to your ViewHolder's constructor. That's the most common oversight when replacing ButterKnife here.
Here's How to Rewrite Your Code
First, let's reference your original ButterKnife setup (abbreviated):
public class FriendsHolder extends RecyclerView.ViewHolder { @BindView(R.id.name) TextView textName; @BindView(R.id.image) CircleImageView imageView; // ... other bound views public FriendsHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); // ButterKnife uses itemView to locate views } }
Now, replace it with this vanilla Android code that mirrors ButterKnife's behavior:
public class FriendsHolder extends RecyclerView.ViewHolder { TextView textName; CircleImageView imageView; // ... declare all your other views here public FriendsHolder(View itemView) { super(itemView); // Critical: Use itemView.findViewById to access views in your item layout textName = itemView.findViewById(R.id.name); imageView = itemView.findViewById(R.id.image); // Make sure to initialize EVERY view that was previously bound with @BindView } }
Common Pitfalls to Avoid
- Forgetting
itemView.: If you skipitemView.and just callfindViewById(R.id.name), the system won't find your views — they're all children of theitemViewpassed to the ViewHolder, not the parent activity/fragment. - Mismatched IDs: Double-check that the ID you pass to
findViewByIdexactly matches the ID in your item XML layout (e.g., if your original @BindView usedR.id.name, don't accidentally useR.id.post_titlelike in your example snippet). - Missing Initializations: Every view that had an
@BindViewannotation needs a correspondingitemView.findViewByIdline. Leaving any out will cause null pointer exceptions or missing UI elements.
Quick Validation Steps
- Go through each view in your ViewHolder and confirm it's initialized with
itemView.findViewById. - Cross-reference each ID with your XML layout to ensure they match perfectly.
- Run your app again — the behavior should now match what you had with ButterKnife.
内容的提问来源于stack exchange,提问作者Mat

