我偶然发现了一个非常有趣的Dependency Injection库ButterKnife.使用ButterKnife它可以轻松地将视图注入活动或片段.
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...
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果使用依赖注入这些观点必须public让Butterknife能注射它(使用private一个异常场的结果fields must not be private or static).
在我过去的项目中,我总是制作所有成员字段(包括视图),private因为我认为这是最佳实践(信息隐藏等)现在我想知道是否有理由不应该制作所有视图public?在这种情况下,我不能使用,ButterKnife但我想使用它,因为它简化了很多代码.