3

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

user2052428
  • 31
  • 1
  • 3

2 Answers2

1

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 IllegalStateExceptions and null references. Also note that you are responsible for calling the appropriate lifecycle methods (i.e. onDestroyView() etc).

Brett Duncavage
  • 2,163
  • 14
  • 16
0

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

Karakuri
  • 38,365
  • 12
  • 84
  • 104