我正在尝试创建一个白日梦应用程序,但似乎找不到任何关于在我的DreamService类中使用片段的文档。
我的意图是在XML文件中使用框架:
<FrameLayout
android:id="@+id/content_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>然后使用FragmentManager将我的片段添加到框架中:
public void onAttachedToWindow( )
{
setContentView(R.layout.daydream);
getFragmentManager().beginTransaction().replace(R.id.content_frag, new ContentFragment(), "ContentFragment")
.commit();
super.onAttachedToWindow();
}在DreamService中似乎没有"getFragmentManager()“或等效的函数,因此这是可能的,我该怎么做呢?
谢谢
发布于 2013-12-08 16:23:28
可以将片段与DreamService结合使用。尽管您可以这样做,但这并不意味着您应该这样做,因为需要注意的是,您的片段必须知道它在Activity和DreamService中正常使用。
以下代码段有效(已在设备上测试):
MyFragment fragment = new MyFragment();
View view = fragment.onCreateView(LayoutInflater.fromContext(this), null, null);
setContentView(view);但是您必须注意,如果您的片段依赖于附加到Activity (例如,调用getResources(),或者需要getActivity()返回非null ),则它必须适当地检查isAdded(),以避免IllegalStateExceptions和null引用。还要注意,您负责调用适当的生命周期方法(即onDestroyView()等)。
发布于 2013-04-07 10:13:59
我觉得你做不到。DreamService是一种服务。它没有FragmentManager的概念。
https://stackoverflow.com/questions/15856942
复制相似问题