当前位置: 代码迷 >> java >> 在Android Studio中导入Butterknife后,注释@InjectView无法正常工作?
  详细解决方案

在Android Studio中导入Butterknife后,注释@InjectView无法正常工作?

热度:37   发布时间:2023-08-02 10:45:47.0

刚刚遇到了奶油刀。 我在gradle(module:app)文件中添加了这行:compile'c??om.jakewharton:butterknife:7.0.1'

它同步没有任何错误。 我可以将'butterknife.Butterknife'导入到我的类文件中,其中导入usualyy。 但是无法导入butterknife.InjectView似乎没有? 有什么建议么?

Butterknife 7.0.0版本包括重命名注释动词的重大变化。 这在更改日志中突出显示并反映在网站中。

Version 7.0.0 *(2015-06-27)*
----------------------------

 * `@Bind` replaces `@InjectView` and `@InjectViews`.
 * `ButterKnife.bind` and `ButterKnife.unbind` replaces `ButterKnife.inject` 
    and `ButterKnife.reset`, respectively.
...

是一本非常好的,最新的用法介绍。

这是最简单的用法:

class ExampleActivity extends Activity {
  @Bind(R.id.title) TextView title;
  @Bind(R.id.subtitle) TextView subtitle;
  @Bind(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}

@InjectView不再可用,并被@BindView取代。 我们必须导入Butterknife依赖项才能使用注释。 更多关于黄油刀的信息: -

@BindView注释可以实现为: -

@BindView(R.id.button_id)

请注意,您需要调用ButterKnife.bind(this); onCreate()方法的主要活动来启用Butterknife注释。 这个实现的一个例子可能是这样的: -

public class MainActivity extends AppCompatibilityActivity{
    @BindView(R.id.editText_main_firstName)
    EditText firstName;
    @BindView(R.id.editText_main_lastName)
    EditText lastName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Needs to be called to enable Butterknife annotations
        ButterKnife.bind(this);

    }
}

如果你在片段中使用Butterknife ,那么使用Butterknife.bind(this,view)视图是片段视图,即: -

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_other_product_category, container, false);
    ButterKnife.bind(this, view);
    return view;
}

显然@InjectView被取代@Bind

你需要打电话给ButterKnife.bind(this); 在你的onCreate()

见: :

  相关解决方案