2013-03-26 141 views
0

我爲片段事務使用以下佈局。我正在使用以下代碼替換片段1 與新片段。我附加布局文件也供您參考。我爲每個listitem點擊執行下面的代碼。Android片段替換問題

代碼:

 Fragment newFragment = new Grades(); 
         android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

          // Replace whatever is in the fragment_container view with this fragment 
         transaction.replace(R.id.fragment1, newFragment); 

          // Commit the transaction 
         transaction.commit(); 
Fragment newFragment = new Teachers(); 
         android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

          // Replace whatever is in the fragment_container view with this fragment 
         transaction.replace(R.id.fragment1, newFragment); 

          // Commit the transaction 
         transaction.commit(); 
<LinearLayout 
       android:id="@+id/slidingPanel" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:gravity="left" 
       android:orientation="vertical" 
       android:background="@android:color/white" 

       > 

<fragment 
        android:id="@+id/fragment1" 
        android:name="com.example.slideoutmenu.Item3" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" /> 

</Linearlayout> 

我懷疑是我應該更換片段1每次當我展現出新的片段或者我應該取代現有的片段,如果這樣我怎麼能取代現有的片段。

回答

1

要更換片段: -

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); 
YourFragment yourFragment = new YourFragment(); 
fragmentTransaction.replace(R.id.top_layout, yourFragment); // top_layout is parent layout/viewgroup where you want to place your new fragment 
fragmentTransaction.commit();