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 aDreamService
.The following snippet works (has been tested on device):
But you must note that if your fragment relies on being attached to an
Activity
(callsgetResources()
, or needsgetActivity()
to return non-null for example), it must checkisAdded()
as appropriate to avoidIllegalStateException
s and null references. Also note that you are responsible for calling the appropriate lifecycle methods (i.e.onDestroyView()
etc).