Steps: Framelayout = framelayout = framelayout = framelayout = Framelayout = framelayout = framelayout Add (resource ID, fragment) Add the fragment to the layout. Commit 5. Switch the displayed fragment with FragmentTransaction. Replace (Resource ID, fragment)Copy the code
acvitity_dynamic.xml <Button android:id="@+id/btn_change" android:layout_width="wrap_content" Android :layout_height="wrap_content" Android :text=" switch "/> <FrameLayout Android :id="@+id/fl_fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/holo_green_light"></FrameLayout>Copy the code
DynamicAcvitity.java public class DynamicActivity extends AppCompatActivity { private Button btn_change; private BlankFragment blank; private SecFragment sec; private Fragment fragment; // Use this variable to indicate which fragment private FragmentManager manager is being displayed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dynamic); blank = new BlankFragment(); sec = new SecFragment(); fragment=blank; manager=getSupportFragmentManager(); // Start a transaction FragmentTransaction =manager.beginTransaction(); transaction.add(R.id.fl_fragment,blank); transaction.commit(); Btn_change = (Button) findViewById(R.i.btn_change); Btn_change. SetOnClickListener (new View. An OnClickListener () {@ Override public void onClick (View v) {/ / after a commit things end cannot reoccupy, To create a new transaction FragmentTransaction Transaction1 = Manager.beginTransaction (); if(fragment instanceof BlankFragment){ fragment=sec; }else { fragment=blank; } transaction1.replace(R.id.fl_fragment,fragment); transaction1.commit(); }});Copy the code
Fragment Problem of nested Fragment
- Use a viewPager nested fragment in the Fragment. Replace getFragmentManager with getChildFragmentManager when obtaining fragmentManager