victor.alm victor.alm - 5 months ago 100
Android Question

@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

Answer

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