Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any simple examples using roboguice with fragments in android?

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?

like image 929
technoviking Avatar asked Nov 27 '11 22:11

technoviking


1 Answers

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.

like image 186
Kingamajick Avatar answered Sep 28 '22 01:09

Kingamajick