在android中使用roboguice和片段的任何简单例子?

tec*_*ing 14 android fragment roboguice

我在找到使用片段+ RoboGuice的工作示例时遇到了问题.当您尝试使用Android片段事务管理器添加/删除片段时,会发生此问题.一旦告诉片段继承自RoboFragment,事务管理器就不再认为该类是片段(因为它扩展了RoboFragment).但是,您可以使用RoboGuice自己的片段管理器,但它也会崩溃.有没有动态添加/删除RoboGuice片段的例子?

Kin*_*ick 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.
}
Run Code Online (Sandbox Code Playgroud)

显然我也实现了onCreateView.

然后,在我的Activity中,我扩展了FragmentActivity,因为我正在使用兼容包.注意,如果您希望与pre API级别11兼容,则必须使用FragmentActivity.如果您只是支持11 plus,则不需要兼容性lib或使用FragementActivity.在我的活动中,我然后使用以下内容将片段添加到我的页面.

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentHolder, new MyFragment());
transaction.commit();
Run Code Online (Sandbox Code Playgroud)

R.id.fragmentHolder的类型是FrameLayout.

一切正常,我可以在我的片段中使用我注入的所有资源和视图.为了完整性,我使用最新的2.0-SNAPSHOT roboguice与针对Android 2.2.1的兼容性-v4库的版本r6.


kon*_*ity 0

Roboguice 1.x 与 compat 库和片段不兼容。您要么必须迁移处于测试阶段的 2.0,要么自己扩展 Fragment* 类。

更多信息请访问:

http://groups.google.com/group/roboguice/browse_thread/thread/2858bc10b83b6beb