How to inject dependencies into any kind of object with Dagger2?

*爱你&永不变心* 提交于 2019-12-03 02:31:52
Kirill Boyarshinov

Inject child fragments instead of BaseFragment. In your case:

public class ListFragment extends BaseFragment {

    @Inject ListFragmentPresenterImpl listFragmentPresenter;

    public static ListFragment newInstance(){
        ListFragment result = new ListFragment();
        return result;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((MainActivity)getActivity()).getComponent().injectFragment(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.list_fragment, container, false);
        Log.d("",listFragmentPresenter.sayHello());  // NPE HERE
        return rootView;
    }
}

And in your Component class:

@AScope
@Component(dependencies = ApplicationComponent.class,
           modules = ActivityModule.class)
interface ActivityComponent {
    void injectActivity(MainActivity activity);
    void injectFragment(ListFragment fragment);
    // Put any more injects here, if BaseFragment has
    // any other children that need to be injected, for example:
    void inject(MapFragment fragment);
    void inject(DetailFragment fragment);
}

Parent -> Child injection is not working in Dagger 2. It was covered here, here and this SO question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!