Android Fragment替换问题

时间:2013-03-26 12:10:11

标签: android fragment replace

我正在使用以下布局进行片段事务处理。我正在替换 fragment1 通过使用以下代码使用新片段。我附加了布局文件也供您参考。我正在为每个listitem点击执行以下代码。

代码:

     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>

我怀疑是每次当我显示一个新片段时应该替换 fragment1 还是应该替换现有片段,如果是,我该如何替换现有片段。

1 个答案:

答案 0 :(得分: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();