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();
}
}
}
在一个新项目中,我开始使用匕首和嵌套片段,在我的脑海中得到了两个问题。 1.片段是否应注入活动或其他片段? 2.在配置更改后注入处理娱乐的片段的正确方法是什么? 我遇到的问题是在上面的代码中,将创建另一个HostedFragment并将其注入HostActivity。
if (savedInstanceState == null) {
ObjectGraph.create(new HostActivityModule()).inject(this);
getFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();
}
修改上述版本可能会避免重复创建HostedFragment,但如果我们需要注射除片段之外的其他注入,则不会在重新创建时注入它们。
任何人都可以帮助我吗?
答案 0 :(得分:0)
我提出了一种方法,我是否正确? 唯一困扰我的是如果在@Module注入中未指定HostedFragment,我无法从图中获取它。
public class HostActivity extends Activity { private static final String FRAGMENT_TAG =“fragment tag”;
private ObjectGraph objectGraph;
private HostedFragment fragment;
@Inject LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host);
// Injecting fields that are required
objectGraph = ObjectGraph.create(new HostActivityModule(this));
objectGraph.inject(this);
// Injecting fragment
fragment = (HostedFragment) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
if (fragment == null) {
fragment = objectGraph.get(HostedFragment.class);
getFragmentManager().beginTransaction().add(R.id.fragment_container, fragment, FRAGMENT_TAG).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,
HostedFragment.class
},
library = true
)
public static class HostActivityModule {
private Context mContext;
public HostActivityModule(Context mContext) {
this.mContext = mContext;
}
@Provides @Singleton HostedFragment provideHostedFragment() {
return new HostedFragment();
}
@Provides @Singleton LocationManager provideLocationManager() {
return (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
}
}
}