[英]Android: Fragments Inside Daydreams
我正在尝试创建一个白日梦应用程序,似乎无法在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()”或等效函数,因此这可能吗,我该怎么做?
谢谢
可以将片段与DreamService结合使用。 尽管只是因为可以,但这并不意味着您应该这样做,因为有些警告必须使您的片段必须知道它通常在(在Activity
)和DreamService
。
以下代码段有效(已在设备上经过测试):
MyFragment fragment = new MyFragment();
View view = fragment.onCreateView(LayoutInflater.fromContext(this), null, null);
setContentView(view);
但您必须注意,如果您的片段依赖于附加到一个Activity
(例如调用getResources()
或需要getActivity()
返回非null),则它必须适当地检查isAdded()
以避免IllegalStateException
和null引用。 还要注意,您负责调用适当的生命周期方法(即onDestroyView()
等)。
我认为您无法做到这一点。 DreamService是一项服务。 它没有FragmentManager的概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.