How to dynamically change a fragment class

Hi I have a linearLayout containing two fragments and I am adding tabs with code to this layout. What I want is when I press tab1, it is normal for the fragment to fill itself from the specified class, but in tab2 I want to change this class to another class. Thanks you

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/frags"> <fragment class="com.tugce.MitsActionBar.DoktorlarFragment" android:id="@+id/frag_title" android:visibility="gone" android:layout_marginTop="?android:attr/actionBarSize" android:layout_width="@dimen/titles_size" android:layout_height="match_parent" /> <fragment class="com.tugce.MitsActionBar.ContentFragment" android:id="@+id/frag_content" android:layout_width="match_parent" android:layout_height="match_parent" /> 
+6
source share
2 answers

Change <fragment/> in xml layout to <FrameLayout/>

 <FrameLayout android:id="@+id/frag_title" android:visibility="gone" android:layout_marginTop="?android:attr/actionBarSize" android:layout_width="@dimen/titles_size" android:layout_height="match_parent" /> <FrameLayout android:id="@+id/frag_content" android:layout_width="match_parent" android:layout_height="match_parent" /> 

and programmatically add fragments:

 FragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.replace(R.id.frag_content, fragment); fragmentTransaction.commit(); 

But first read this one .

+24
source

Shortest fragment call version

 getFragmentManager().beginTransaction().replace(R.id.splash_container, new ExampleFragment()).addToBackStack(null).commit(); 

addToBackStack(null) is optional if you want to keep the fragment on the stack or not.

+3
source

Source: https://habr.com/ru/post/897385/


All Articles