View dependency injection with dagger 2

前端 未结 3 928
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 05:09

I have a custom view extending a TextView. Where should I call my component to inject the view?

component.inject(customTextView);
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-09 05:59

    My general solution for that kind of thing is 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);
            }
        }
    

提交回复
热议问题