简体   繁体   English

Android:白日梦中的碎片

[英]Android: Fragments Inside Daydreams

I am trying to create a daydream app and cannot seem to find any documentation on the use of fragments within my DreamService class. 我正在尝试创建一个白日梦应用程序,似乎无法在DreamService类中找到有关使用片段的任何文档。

My intention was to use a frame the in the XML file: 我的意图是在XML文件中使用框架:

    <FrameLayout 
      android:id="@+id/content_frag"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      />

And then use a FragmentManager to add my fragment into the frame: 然后使用FragmentManager将我的片段添加到框架中:

    public void onAttachedToWindow( )
{
    setContentView(R.layout.daydream);

    getFragmentManager().beginTransaction().replace(R.id.content_frag, new ContentFragment(), "ContentFragment")
        .commit();

    super.onAttachedToWindow();
}

There seems to be no "getFragmentManager()" or equivalent function within DreamService, therefore is this possible, and how do I do it? DreamService中似乎没有“ getFragmentManager()”或等效函数,因此这可能吗,我该怎么做?

Thanks 谢谢

It is possible to use a fragment in conjunction with DreamService. 可以将片段与DreamService结合使用。 Although just because you can, it doesn't mean you should because there are some caveats that your fragment must be aware of it is used normally (in an Activity ) and in a DreamService . 尽管只是因为可以,但这并不意味着您应该这样做,因为有些警告必须使您的片段必须知道它通常在(在Activity )和DreamService

The following snippet works (has been tested on device): 以下代码段有效(已在设备上经过测试):

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

But you must note that if your fragment relies on being attached to an Activity (calls getResources() , or needs getActivity() to return non-null for example), it must check isAdded() as appropriate to avoid IllegalStateException s and null references. 但您必须注意,如果您的片段依赖于附加到一个Activity (例如调用getResources()或需要getActivity()返回非null),则它必须适当地检查isAdded()以避免IllegalStateException和null引用。 Also note that you are responsible for calling the appropriate lifecycle methods (ie onDestroyView() etc). 还要注意,您负责调用适当的生命周期方法(即onDestroyView()等)。

I don't think you can do this. 我认为您无法做到这一点。 DreamService is a Service. DreamService是一项服务。 It has no concept of a FragmentManager. 它没有FragmentManager的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM