使用 Roboguice 依赖注入以编程方式实例化 Android 个片段

Instantiate Android fragments programaticly while using Roboguice Dependency Injection

我有一个 Activity 带有一个 ViewGroup,我想根据用户流用它来替换几个片段(所以我要么显示一个片段,要么显示另一个片段)。

    (...)
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="276dp"
        android:layout_gravity="center_horizontal|bottom">
    </FrameLayout>
    (...)

要设置片段,我使用以下代码:

private void setBottomFragment(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

如果我自己用 new 实例化片段,它会起作用:

setBottomFragment(new InformationFragment());

但是,我不想自己实例化它。我希望我的片段实例由我的依赖管理框架管理(我正在使用 Roboguice

所以我想做这样的事情:

@ContentView(R.layout.activity_scan)
public class ScanActivity extends RoboFragmentActivity {

    @InjectFragment(R.id.information_fragment)
    private InformationFragment informationFragment;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBottomFragment(informationFragment);
    }
}

通过这样做,我也可以在我的 Fragment 上使用依赖注入,而不必自己寻找组件。

    public class InformationFragment extends RoboFragment {

        // I'll have an event handler for this button and I don't want to be finding it myself if I can have it injected instead.
        @InjectView(R.id.resultButton)
        private Button resultButton;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_information, container, false);
        }
    }

所以基本上我的问题是:如何在使用像 Roboguice 这样的依赖注入框架时以编程方式实例化片段?

我在 Roboguice 文档中所能找到的所有内容都是带有片段的 DI 示例,这些片段最初是用视图呈现的,而不是之后动态添加的,就像我正在尝试做的那样。这让我相信我在组件的生命周期或 Roboguice 处理 DI 的方式中遗漏了一些东西。

任何解决此问题的想法或正确方向的指示都会非常有帮助。

我自己找到了答案,因为它可能对其他人有帮助,所以我将 post 放在这里。

它比我预期的要简单得多(也有点明显)。因为在第一次加载 activity 时片段不是视图的一部分,所以我们不能使用 @InjectFragment。应该改用@Inject,因此该片段被视为任何其他非视图依赖项。

这意味着我的 activity 应该是这样的:

@ContentView(R.layout.activity_scan)
public class ScanActivity extends RoboFragmentActivity {

    @Inject // This is all that needs to change
    private InformationFragment informationFragment;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBottomFragment(informationFragment);
    }
}

就这么简单...