我假設你遇到的問題是沒有一個膨脹的視圖來添加片段,因爲原始片段FRAG4_TAG在你嘗試添加它之前沒有被膨脹。
您可以將足夠的信息傳遞給參數中的FRAG4_TAG,讓它知道在視圖膨脹後,它應該在onCreateView期間創建並添加片段(或者您需要的所有片段)給自己。 ..
該活動的佈局...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="MyActivity"/>
<LinearLayout
android:orientation="vertical"
android:id="@+id/main_frag_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
的活動...
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragOne = new MyFragment();
Bundle arguments = new Bundle();
arguments.putBoolean("shouldYouCreateAChildFragment", true);
fragOne.setArguments(arguments);
ft.add(R.id.main_frag_container, fragOne);
ft.commit();
}
}
碎片的佈局...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="20dp">
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Some fragment"/>
<LinearLayout
android:orientation="vertical"
android:id="@+id/frag_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
片段...
public class MyFragment extends Fragment {
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.frag_layout, container, false);
boolean shouldCreateChild = getArguments().getBoolean("shouldYouCreateAChildFragment");
if (shouldCreateChild) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragTwo = new MyFragment();
Bundle arguments = new Bundle();
arguments.putBoolean("shouldYouCreateAChildFragment", false);
fragTwo.setArguments(arguments);
ft.add(R.id.frag_container, fragTwo);
ft.commit();
}
return layout;
}
}
這個例子包括了那些你需要動態片段添加到尚未膨脹並添加到層次結構中的片段的情況。將碎片添加到已被充氣並添加到層次結構中的碎片就像只需指定您希望通過ID添加到的目標碎片容器一樣簡單,就像您通常那樣。
你試過了嗎?我不認爲如果它是possilbe片段不能包含其他片段...使用視圖爲(我面臨同樣isuse ...我已經有片段讓我們調用左列表視圖和DetailsPane現在我wana ViewPager在DetailsPane中。 ..所以我建立每個傳呼頁面的片段...但它總是以事務提交錯誤結束...經過一些研究後,我發現這個http:// stackoverflow。com/questions/5268361/fragments-in-action-bar-tab-fragments – Selvin
是的,我試過了,但沒有成功。感謝您的評論 – Waypoint
http://stackoverflow.com/questions/7700226/display-fragment-viewpager-within-a-fragment/7700305#7700305,請檢查此解決方案是否適合您。在另一個片段內插入使用片段是一個工作。 –