Any simple examples using roboguice with fragments in android?

前端 未结 2 1721
攒了一身酷
攒了一身酷 2021-02-04 07:49

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

2条回答
  •  悲&欢浪女
    2021-02-04 08:04

    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.

提交回复
热议问题