1

i wanted to inject dependency in my fragments how can i do this with dagger. i'm trying to get the activityComponent object from the MainActivity class. But if i have multiple classes using the same fragment do i need to type cast by checking the instance.Is there any simple way...

public class RepositoryFragment extends Fragment implements 
               RepositoryContract.View {
        @Inject
        RepositoryContract.Presenter presenter;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

            View view = inflater.inflate(R.layout.fragment_repository, container, false);

            // obtain Dagger 2 ActivityComponent from Actiity
            ActivityComponent activityComponent = ((MainActivity)getActivity()).getActivityComponent();
            // Inject dependencies
            activityComponent.inject(this);

            presenter.setView(this);
            ...
            return view;
        }
    }
avez raj
  • 2,055
  • 2
  • 22
  • 37
  • follow this link https://stackoverflow.com/questions/32113953/dagger-2-on-android-inject-same-dependency-in-activity-and-retained-fragment – Ankita Sep 20 '17 at 11:32
  • _But if i have multiple classes using the same fragment do i need to type cast_ You can always have your Activities implement an interface – David Medenjak Sep 27 '17 at 18:33
  • this problem is solved by having a hash map which will contain whenever we try to get the component we can search in the hash map if it is present it will return it for as many fragments we need. – avez raj Sep 28 '17 at 06:51

0 Answers0