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
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(); } }); }
The correct answer is to use the See the Butterknife home page. @Nullable annotation.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 ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With