如何在运行时在Dagger 2中传递方法依赖项

时间:2017-07-21 10:22:00

标签: java android dependency-injection dagger-2

我有点复杂的情况。让我先发布代码然后解释FragmentModule

 @Module
    public class FragmentModule
    {
        @Provides
        public static PickerDashboardFragment providesPickerDashboard()
        {
            PickerDashboardFragment fragment = new PickerDashboardFragment();
            return fragment;
        }

        @Provides
        public static PickingFragment providesPickingFragment()
        {
            PickingFragment fragment = new PickingFragment();
            return fragment;
        }

        @Provides
        public static PickingItemsFragment providesPickingItemsFragment()
        {
            PickingItemsFragment fragment = new PickingItemsFragment();
            return fragment;
        }

        **Note this**
        @Provides
        public static StagedItemsFragment providesStagedItemsFragment(ArrayList<PickJava> pickedList)
        {
            Bundle arguments = new Bundle();
            arguments.putParcelableArrayList("picked_list", pickedList);
            StagedItemsFragment fragment = new StagedItemsFragment();
            return fragment;
        }
    }

以下是FragmentComponent

@Component(modules = {FragmentModule.class, FragmentUtilsModule.class})
public interface FragmentComponent
{
    void inject(PickerDashboardActivity target);

    void inject(PickerDashboardFragment target);

    void inject(PickingFragment target);

   **Note this**
    StagedItemsFragment stagedItemsFragment();
}

非常重要的一部分。请求注入,这就是我在Fragment中构建我的组件的方式。

    public class PickingFragment extends Fragment{

    FragmentComponent component

    @Inject
        PickingItemsFragment pickingItemsFragment;

    @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

      component = DaggerFragmentComponent
                    .builder()
                    .fragmentUtilsModule(new FragmentUtilsModule(this))
                    .build();
            component.inject(this);
    }

**Note this**
@Override
public void onClick(View v)
{
    // Here i need StagedItemsFragment stagedItemsFragment(); from FragmentComponent
replaceNestedFragment(component.stagedItemsFragment());
}

但问题是fragmentComponent已经构建完毕。现在您可以在FragmentModule providesStagedItemsFragment方法中看到,需要ArrayList<PickJava> pickedList作为参数。我怎么能通过这个。如果需要,请提供帮助或询问更多详细信息。

0 个答案:

没有答案