public class HostActivity extends Activity {
@Inject HostedFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host);
ObjectGraph.create(new HostActivityModule()).inject(this);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
public static class HostedFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_hosted, container, false);
}
}
@Module(injects = HostActivity.class)
public static class HostActivityModule {
@Provides @Singleton
HostedFragment provideHostedFragment() {
return new HostedFragment();
}
}
}
In a new project, I start to use dagger and nested fragment and come got a 2 questions in my mind. 1. Should fragment be injected into activity or another fragment? 2. What is the correct way to inject fragment which handle recreation after configuration change? The problem I encounter is in the above code, another HostedFragment will be created and injected into HostActivity.
if (savedInstanceState == null) {
ObjectGraph.create(new HostActivityModule()).inject(this);
getFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();
}
Modifying to the above version might avoid duplicate HostedFragment being created but if we need injections other then fragment, they are not injected during recreation.
Can anyone help me?