ragdroid / Dahaka

Demo project for Dagger 2
Apache License 2.0
207 stars 35 forks source link

why fragment need construction method?? #14

Open l007001 opened 6 years ago

l007001 commented 6 years ago

public class ProfileFragment extends BaseFragment implements ProfileContract.View {

@Inject
public ProfileFragment() {
    // Required empty public constructor for Injection
}

private FragmentProfileBinding dataBinding;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_profile, container, false);
    dataBinding = DataBindingUtil.bind(view);
    return view;
}

@Override
public void showModel(ProfileModel model) {
    dataBinding.setModel(model);
}

}

The official document does not say that this construction method needs to be added. Can you explain it for me? thanks!

ragdroid commented 6 years ago

Hey @l007001

This has actually got nothing much to do with dagger-android.

In the official documentation, we have a section to make a Fragment as injection target (ability to extract out boilerplate code for fragment injection with AndroidInjection.inject(), whereas the empty public constructor with @Inject annotation in the above case is actually used to provide ProfileFragment as a dependency to HomeActivity.

Inside our HomeActivity, we are actually injecting ProfileFragment dependency :

class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {

    @Inject ProfileFragment profileFragment;
// ...
}

For now let us forget that the ProfileFragment dependency is actually a Fragment. Let us assume that this dependency was actually like a normal dependency : Profile.

Now there are two ways of providing this dependency to HomeActivity

  1. Inside the HomeActivtyModule we can create a provider method as follows :
fun provideHomeFragment(): ProfileFragment {
  return ProfileFragment()
}

OR

  1. We can have an @Inject constructor inside our ProfileFragment like I have done.

Both the above ways will provide ProfileFragment as any other dependency to HomeActivity.

Hope this makes sense