madan V
madan V

Reputation: 844

Android Fragment replacement issue

i am using the following layout for fragment transaction. i am replacing the fragment1 with new fragments by using the following code.i am attaching the layout file also for your reference. i am executing the below code for every listitem click.

Code:

     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>

my doubt is should i replace the fragment1 everytime when i show a new fragment or should i replace the existing fragment if so how can i replace the existing fragment.

Upvotes: 0

Views: 213

Answers (1)

user2179988
user2179988

Reputation: 11

To replace the fragment:-

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();

Upvotes: 1

Related Questions