Butterknife观注 [英] Butterknife View injection

查看:344
本文介绍了Butterknife观注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一个名为 Butterknife 很有意思的依赖注入库。 USINT Butterknife 很容易地注入浏览到活动或片段。

I stumbled across a very interesting Dependency Injection library called Butterknife. Usint Butterknife it's easily possible to inject Views into activities or fragments.

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

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.inject(this);
    // TODO Use "injected" views...
  }
}

然而,如果使用依赖注入这些观点一定是公开 Butterknife 能够注入它。 (使用私人字段导致异常字段必须不能是私有的或静态的。

However if using Dependency Injection those Views must be public so that Butterknife can inject it. (Using private fields results in an exception fields must not be private or static..

在我过去的项目中,我总是让所有的成员字段(包括视图)私人,因为我认为这是最好的做法(信息隐藏等。)现在,我不知道是否有一个原因,我们不应该让所有的意见公开?在这种情况下,我不能使用 Butterknife ,但我想用它,因为它简化了codeA不少。

In my past project I always made all the member fields (including the views) private as I thought this is best practice (information hiding etc..) Now I am wondering if there is a reason why one should NOT make all the views public? In this case I cannot use Butterknife but I want to use it because it simplifies the code a lot.

推荐答案

首先,黄油刀是不是一个依赖注入库。你可以把它作为一个样板减少库,因为它是所有替换 findViewById 和各种 setXxxListener 电话。

First off, Butter Knife is not a dependency injection library. You can think of it as a boilerplate reduction library since all it does is replace findViewById and various setXxxListener calls.

这黄油刀需要的观点不私的原因是,实际上是产生code这台场。在code,它产生的生活在同一个包类这就是为什么字段必须是包私有,保护,或公开。如果该字段是私人所产生的code将无法编译,因为它不能访问私有字段。

The reason that Butter Knife requires views not be private is that is actually generates code which sets the fields. The code that it generates lives in the same package as your class which is why the field must be package-private, protected, or public. If the field was private the generated code would fail to compile since it cannot access the private field.

生成的code看起来是这样的:

The generated code looks something like this:

public static void inject(ExampleActivity target, ExampleActivity source) {
  target.title = (TextView) source.findViewById(R.id.title);
  target.subtitle = (TextView) source.findViewById(R.id.subtitle);
  target.footer = (TextView) source.findViewById(R.id.footer);
}

当你调用 ButterKnife.inject(本)看起来了这个生成类,并调用注射方法你的为ExampleActivity 实例作为目的的领域和源 findViewById 调用。

When you call ButterKnife.inject(this) it looks up this generate class and calls the inject method with your instance of ExampleActivity as both the destination for the fields and the source for findViewById calls.

这篇关于Butterknife观注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆