Any simple examples using roboguice with fragments in android?

[亡魂溺海] 提交于 2019-12-03 07:20:30

问题


I'm having issues finding a working example of using fragments + RoboGuice. The problem happens when you attempt to add/remove fragments with the Android fragment transaction manager. Once you tell the fragment to inherit from RoboFragment the transaction manager no longer thinks the class is a fragment (because it extends RoboFragment). You can however use RoboGuice's own fragment manager but it also crashes. Is there any examples out there of adding/removing RoboGuice fragments dynamically?


回答1:


I've recently started using fragments on a new project, and the following is the code I'm using

I'm not inheriting from the RoboFragment class, but I'm doing exactly the same by adding the following lines to my onCreate and onViewCreated methods. Inheriting from RoboFragment shouldn't behave any different, in fact this is what RoboFragment looks like.

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.
}

Obviously I've also implemented onCreateView.

Then, in my Activity I extend FragmentActivity as I'm using the compatibility package. Note, you must use FragmentActivity if your wanting compatibility with pre API level 11. If you're just supporting 11 plus you don't need the compatibility lib or to use FragementActivity. In my activity I'm then using the following to add the fragment to my page.

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentHolder, new MyFragment());
transaction.commit();

The type of R.id.fragmentHolder is a FrameLayout.

Everything works fine with this and I'm able to use all my injected resources and views in my fragment. For completeness I'm using the latest 2.0-SNAPSHOT of roboguice with version r6 of the compatibity-v4 library against Android 2.2.1.




回答2:


Roboguice 1.x is not compatible with the compat library and fragments. You will either have to move 2.0 which is in beta or extend the Fragment* classes yourselves.

More information is available at:

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



来源:https://stackoverflow.com/questions/8289660/any-simple-examples-using-roboguice-with-fragments-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!