【发布时间】: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