30

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

4

3 回答 3

46

只需@Optional在方法顶部添加注释,如下面的代码所示:

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

有一种情况是您R.id.inflated_bt1Activity. 对于这种情况,您必须使用@Optional注释。

当您@OnClick在源代码中仅使用注释时,YourClass$$ViewInjector如下所示:

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

并且该方法在视图findRequiredView为时抛出。IllegalStateExceptionnull

但是当您使用额外@Optional的注释时,生成的代码如下所示

view = finder.findOptionalView(source, 2131230789);
if (view != null) {
  view.setOnClickListener(
    new butterknife.internal.DebouncingOnClickListener() {
      @Override public void doClick(
        android.view.View p0
      ) {
        target.onClick();
      }
    });
}
于 2015-04-01T12:29:09.947 回答
36

正确答案是使用@Nullable注解。请参阅Butterknife 主页使用示例:

import android.support.annotation.Nullable;

@Nullable
@OnClick(R.id.maybe_missing)
void onMaybeMissingClicked() {
    // TODO ...
}

编辑:

在我写下这个答案并被接受的那一年,Butterknife 文档发生了变化,目前完成此操作的首选方法是使用@Optional注释。由于这是公认的答案,我觉得更新它以解决当前的做法很重要。例如:

import butterknife.Optional;

@Optional
@OnClick(R.id.maybe_missing)
void onMaybeMissingClicked() {
    // TODO ...
}
于 2016-01-21T18:00:06.513 回答
3
@Nullable
@OnClick({R.id.bt1, R.id.bt2, R.id.inflated_bt1, R.id.inflated_bt2})
public void onClick(View view) {
    // ...
}

如果您像 Butterknife docs 和 @AutonomousApps 所说的那样包含 nullable,那么即使您没有一直使用它们,您也可以包含尽可能多的 id。

如果您不使用 appcompact 库,请记住包含注释支持库。检查此链接支持注释

于 2016-06-27T06:59:52.523 回答