0

我正在使用以下布局进行片段交易。我正在使用以下代码将片段1 替换为 新片段。我还附上了布局文件以供您参考。我正在为每个列表项单击执行以下代码。

代码:

     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,还是应该替换现有片段,如果是这样,我该如何替换现有片段。

4

1 回答 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();
于 2013-05-06T04:30:29.253 回答