Search code examples
androidandroid-studiomobilereplacebutterknife

Error convert findByID to @BindView when upgrading ButterKnife


I have a project from someone else, but when I opened it there was some error. Butterknife has an error, it displays: "error: can't find findById (View, int) notation", I know that it has been replaced by @BindView, I changed findById to @BindView but only findById 2 parameters while @BindView only has 1. How do I convert it?

This is new code:

@BindView(R.id.fab_subitem_image) ImageView image;
private void addActionItem(@NonNull LayoutInflater inflater, int index,
    @NonNull final FABAction item) {
    // Inflate & Configure item
    final View subItem = inflater.inflate(R.layout.fab_subitem, mItemContainer, false);

    image.setBackgroundColor(item.mBgColor);

This is old code:

private void addActionItem(@NonNull LayoutInflater inflater, int index,
    @NonNull final FABAction item) {
    // Inflate & Configure item
    final View subItem = inflater.inflate(R.layout.fab_subitem, mItemContainer, false);
    ImageView image = ButterKnife.findById(subItem, R.id.fab_subitem_image); <--This is old code

    image.setBackgroundColor(item.mBgColor);

Solution

  • You have to tell ButterKnife to generate bindings for the object that contains @BindView annotations. You should call ButterKnife.bind(this, subItem) after inflation:

    @BindView(R.id.fab_subitem_image) ImageView image;
    
    private Unbinder unbinder;
    
    private void addActionItem(@NonNull LayoutInflater inflater, int index, @NonNull final FABAction item) {
        // Inflate & Configure item
        final View subItem = inflater.inflate(R.layout.fab_subitem, mItemContainer, false);
        // Generate bindings
        unbinder = ButterKnife.bind(this, subItem);
    
        image.setBackgroundColor(item.mBgColor);
        ...
    }
    
    ...
    
    @Override
    public void onDestroyView(View view) {
        // Unbind when bindings are no longer needed eg. in onDestroyView of a Fragment
        unbinder.unbind()
    }
    

    See the documentation for more information.