Android:白日梦中的碎片

问题描述:

我正在尝试创建一个白日梦应用程序,并且似乎无法在我的DreamService类中找到有关碎片使用的任何文档。Android:白日梦中的碎片

我的目的是使用框架的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(); 
} 

似乎没有“ getFragmentManager()“或DreamService中的等价函数,因此这是可能的,我该怎么做?

谢谢

+3

我可以提名为“本月问题标题”奖吗? – dmon 2013-04-06 23:04:32

我不认为你可以这样做。 DreamService是一项服务。它没有FragmentManager的概念。

可以将一个片段与DreamService结合使用。虽然只是因为你可以,但这并不意味着你应该这样做,因为你的片段必须知道它的一些注意事项(Activity)和DreamService

下面的代码片断作品(对器件进行了测试):

MyFragment fragment = new MyFragment(); 
View view = fragment.onCreateView(LayoutInflater.fromContext(this), null, null); 
setContentView(view); 

但你必须注意,如果您的片段依赖于被连接到Activity(电话getResources(),或者需要getActivity()返回非空例如),它必须适当检查isAdded()以避免IllegalStateException和空引用。还请注意,您有责任调用适当的生命周期方法(即onDestroyView()等)。