[英]Android: Fragments Inside Daydreams
我正在嘗試創建一個白日夢應用程序,似乎無法在DreamService類中找到有關使用片段的任何文檔。
我的意圖是在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();
}
DreamService中似乎沒有“ getFragmentManager()”或等效函數,因此這可能嗎,我該怎么做?
謝謝
可以將片段與DreamService結合使用。 盡管只是因為可以,但這並不意味着您應該這樣做,因為有些警告必須使您的片段必須知道它通常在(在Activity
)和DreamService
。
以下代碼段有效(已在設備上經過測試):
MyFragment fragment = new MyFragment();
View view = fragment.onCreateView(LayoutInflater.fromContext(this), null, null);
setContentView(view);
但您必須注意,如果您的片段依賴於附加到一個Activity
(例如調用getResources()
或需要getActivity()
返回非null),則它必須適當地檢查isAdded()
以避免IllegalStateException
和null引用。 還要注意,您負責調用適當的生命周期方法(即onDestroyView()
等)。
我認為您無法做到這一點。 DreamService是一項服務。 它沒有FragmentManager的概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.