我有一个自定义视图扩展TextView
。我应该在哪里调用我的组件来注入视图?
component.inject(customTextView);
所以,我发现我需要在我的自定义视图的构造函数中添加注入(在所有这些中,或者调用另一个)
例:
public class CustomTextView extends TextView {
@Inject
AnyProvider anyProvider;
public CustomTextView(Context context) { this(context, null); }
public CustomTextView(Context AttributeSet attrs) {
super(context, attrs);
Application.getComponent(context).inject(this);
}
}
我对这类事情的一般解决方案就是这样
public class WelcomeView
extends LinearLayout {
private static final String TAG = "WelcomeView";
public WelcomeView(Context context) {
super(context);
init(context);
}
public WelcomeView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public WelcomeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(21)
public WelcomeView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context) {
if(!isInEditMode()) {
Application.getComponent(context).inject(this);
}
}
更新:自从2.10版本的Dagger这个答案无效。
自定义视图:
public class CustomView extends View {
@Inject
AnyObject anyObject;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
MainActivity mainActivity = (MainActivity) getContext();
mainActivity.getComponent().inject(CustomView.this);
}
}
活动:
ActivityComponent mComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mComponent = DaggerActivityComponent.builder()
.appComponent(getApp().getAppComponent())
.activityModule(new ActivityModule(MainActivity.this))
.build();
mComponent.inject(MainActivity.this);
...
}
public ActivityComponent getComponent() {
return mComponent;
}
具有活动范围的Dagger2组件:
@ActivityScope
@Component(dependencies = AppComponent.class, modules = {ActivityModule.class})
public interface ActivityComponent extends AppComponent {
void inject(MainActivity mainActivity);
void inject(CustomView customView);
}
范围:
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {}