【问题标题】:Instantiate Android fragments programaticly while using Roboguice Dependency Injection在使用 Roboguice 依赖注入时以编程方式实例化 Android 片段
【发布时间】:2016-05-10 03:01:32
【问题描述】:

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

    (...)
    <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 的方式中遗漏了一些东西。

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

【问题讨论】:

  • 你是否在片段中实现了生命周期方法 onCreateView,布局变得膨胀?
  • 是的,我创建了这个方法。或者 IDE 在我创建片段时做了。我将编辑原始问题以说明这一点。

标签: android android-fragments dependency-injection roboguice


【解决方案1】:

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

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

这意味着我的活动应该是这样的:

@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);
    }
}

就这么简单……

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 2014-06-16
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多