Dahaka
Dahaka copied to clipboard
why fragment need construction method??
public class ProfileFragment extends BaseFragment<ProfileContract.Presenter> 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!
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
- Inside the
HomeActivtyModulewe can create a provider method as follows :
fun provideHomeFragment(): ProfileFragment {
return ProfileFragment()
}
OR
- We can have an
@Injectconstructor inside ourProfileFragmentlike I have done.
Both the above ways will provide ProfileFragment as any other dependency to HomeActivity.
Hope this makes sense