简体   繁体   中英

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.

My intention was to use a frame the in the XML file:

    <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:

    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?

Thanks

It is possible to use a fragment in conjunction with 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 .

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. Also note that you are responsible for calling the appropriate lifecycle methods (ie onDestroyView() etc).

I don't think you can do this. DreamService is a Service. It has no concept of a FragmentManager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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