Android Dagger-2 how to provide the dependency for method parameters

前端 未结 2 1525
無奈伤痛
無奈伤痛 2021-01-27 09:11

I have a module FragmentModule

@Module
public class FragmentModule
{
    @Provides
    public static PickerDashboardFragment providesPickerDashboard(int status,          


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 09:41

    Add attributes and Provides methods to your module like this:

    @Module
    public class FragmentModule
    {
    
        private final int status;
        private final String name;
        private final Object someComplexObject;
    
        public FragmentModule(int status, String name, Object someComplexObject) {
            this.status = status;
            this.name = name;
            this.someComplexObject = someComplexObject;
        }
    
        @Provides
        int providesStatus() {
            return status;
        }
    
        @Provides
        String providesName() {
            return name;
        }
    
        @Provides
        Object providesSomeComplexObject() {
            return someComplexObjext;
        }
    
        @Provides
        public static PickerDashboardFragment providesPickerDashboard(int status, String name, Object someComplexObject)
        {
            PickerDashboardFragment fragment = new PickerDashboardFragment();
            Bundle b = new Bundle();
            b.putInt("status", status);
            b.putString("name", name);
            b.putInt("object", someComplexObject);
            fragment.setArguments(bundle);
            return fragment;
        }
    
        @Provides
        public static PickingFragment providesPickingFragment()
        {
            PickingFragment fragment = new PickingFragment();
            return fragment;
        }
    }
    

    Having a module providing ints and Strings will probably make you use some qualifiers (such as Named) in order to avoid collisions

提交回复
热议问题