使用匕首2查看依赖注入

时间:2016-03-23 18:31:46

标签: java android view dependency-injection dagger-2

我有一个自定义视图,扩展了TextView。我应该在哪里调用我的组件来注入视图?

component.inject(customTextView);

3 个答案:

答案 0 :(得分:6)

所以,我发现我需要在自定义视图的构造函数中添加注入(在所有这些中,或者调用另一个)

示例:

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);
   }
}

答案 1 :(得分:3)

我对此类事情的一般解决方案是

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 :(得分:2)

更新:从Dagger的2.10版本开始,此答案无效。

自定义视图:

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 {}