Search code examples
androidonclickoption-typebutterknife

@OnClick array with optional ids (ButterKnife)


I have an activity that inflates a view when a web request finished. Some of the widgets of this view have to be attached to one onClick method, so I have:

@OnClick({R.id.bt1, R.id.bt2, R.id.inflated_bt1, R.id.inflated_bt2})
public void onClick(View view) {
    // ...
}

As R.id.inflated_bt1 and R.id.inflated_bt2 don't exist when the app is created, it throws an exception suggesting to set an @Optional annotation.

Required view 'inflated_bt1' with ID XXXXXXXX for method 'onClick' was not found. If this view is optional add '@Optional' annotation.

Is there a way to set some of the views with the @Optional annotation and inject them when the view is inflated? Or, is there another way to do it?

Thank you


Solution

  • The correct answer is to use the @Nullable annotation. See the Butterknife home page. Usage example:

    import android.support.annotation.Nullable;
    
    @Nullable
    @OnClick(R.id.maybe_missing)
    void onMaybeMissingClicked() {
        // TODO ...
    }
    

    EDIT:

    In the year since I wrote this answer and it was accepted, the Butterknife docs changed, and the current preferred method for accomplishing this is to use the @Optional annotation. Since this is the accepted answer, I feel it important to update it to address current practice. For example:

    import butterknife.Optional;
    
    @Optional
    @OnClick(R.id.maybe_missing)
    void onMaybeMissingClicked() {
        // TODO ...
    }