我在找到使用片段+ RoboGuice的工作示例时遇到了问题。当您尝试使用Android片段事务管理器添加/删除片段时,会发生此问题。一旦告诉片段继承自RoboFragment,事务管理器就不再认为该类是片段(因为它扩展了RoboFragment)。但是,您可以使用RoboGuice自己的片段管理器,但它也会崩溃。有没有动态添加/删除RoboGuice片段的例子?
答案 0 :(得分:13)
我最近开始在新项目中使用片段,以下是我正在使用的代码
我不是继承自RoboFragment类,但我通过在onCreate和onViewCreated方法中添加以下行来完全相同。从RoboFragment继承不应该有任何不同,实际上这就是RoboFragment的样子。
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RoboGuice.getInjector(getActivity()).injectMembersWithoutViews(this);
}
public void onViewCreated(final View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RoboGuice.getInjector(getActivity()).injectViewMembers(this);
// Do whatever with your injected views.
}
显然我也实现了onCreateView。
然后,在我的Activity中,我使用compatibility package扩展了FragmentActivity。注意,如果您希望与pre API级别11兼容,则必须使用FragmentActivity。如果您只是支持11 plus,则不需要兼容性lib或使用FragementActivity。在我的活动中,我然后使用以下内容将片段添加到我的页面。
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentHolder, new MyFragment());
transaction.commit();
R.id.fragmentHolder的类型是FrameLayout。
一切正常,我可以在我的片段中使用我注入的所有资源和视图。为了完整性,我使用最新的2.0-SNAPSHOT roboguice与针对Android 2.2.1的兼容性-v4库的r6版本。
答案 1 :(得分:0)
Roboguice 1.x与compat库和片段不兼容。你要么必须移动处于测试阶段的2.0,要么扩展Fragment *类。
更多信息请访问:
http://groups.google.com/group/roboguice/browse_thread/thread/2858bc10b83b6beb