@OnClick array with optional ids (ButterKnife)

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 ...
}

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

If you include nullable as said by Butterknife docs and also by @AutonomousApps then you can include as may as ids even though you are not using them all the time.

Remember to include annotation support library if you are not using appcompact library. Check this link Support Annotations


Just add @Optional annotation on the top of your method as is shown in the code below:

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

There is a case where you don't have R.id.inflated_bt1 in the layout xml which you use on your Activity. For case like this you have to use @Optional annotation.

When you use only @OnClick annotation in YourClass$$ViewInjector source code looks like below:

view = finder.findRequiredView(source, 2131230789, "method 'onClick'");
view.setOnClickListener(
  new butterknife.internal.DebouncingOnClickListener() {
    @Override public void doClick(
      android.view.View p0
    ) {
      target.onClick();
    }
  });

and the method findRequiredView throws IllegalStateException when view is null.

But when you use additionally @Optional annotation, generated code looks like below

view = finder.findOptionalView(source, 2131230789);
if (view != null) {
  view.setOnClickListener(
    new butterknife.internal.DebouncingOnClickListener() {
      @Override public void doClick(
        android.view.View p0
      ) {
        target.onClick();
      }
    });
}