Android manages fragments and androidfragments in an Activity
To manage fragments in an Activity, you need to use FragmentManager. To get it, you need to call the getFragmentManager () method in the Activity. Next, let's take a look at it.
FragmentManager
To manage fragments in an Activity, you need to use FragmentManager.
To get it, call the getFragmentManager () method in the Activity.
Because the FragmentManager API was introduced in Android 3.0, that is, API level 11, for earlier versions, FragmentActivity in the support library should be used and the getSupportFragmentManager () method should be used.
Jobs that can be done with FragmentManager include:
Get the fragment in the Activity.:
Use the findFragmentById () or findFragmentByTag () method.
Bring back stack to fragment:
PopBackStack (): The last fragment conversion in back stack is displayed. If no stack exists, false is returned.
This function is asynchronous: It adds the pop-up stack request to the queue, but this action will not be executed until the application returns to the event loop.
Add a listener to the back stack.:
AddOnBackStackChangedListener ()
Discovery Fragment Transactions
When using Fragment, you can perform some actions through user interaction, such as adding, removing, and replacing.
All these changes constitute a set, which is called a transaction.
You can call the method in FragmentTransaction to process this transaction, and store the transaction in the back stack managed by the activity. This allows you to perform the rollback operation of the fragment change.
You can get an instance of the FragmentTransaction class as follows:
FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Each transaction is a set of changes executed at the same time.
Use the add (), remove (), replace () Methods to add all the required changes, and then call the commit () method to apply these changes.
Before the commit () method, you can call addToBackStack () to add the transaction to the back stack. The back stack is managed by the activity. When you press the return key, the status of the last fragment is returned.
For example, the following code replaces the previous fragment with a new fragment, and stores the previous status in the back stack.
// Create new fragment and transaction Fragment newFragment = new ExampleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit();
In this example, newFragment will replace fragment in the R. id. fragment_container container. If not, a new fragment will be added directly.
By calling addToBackStack (), a series of transformations of commit () are stored as a transaction in the back stack. you can press the Back key to return the status before the previous conversion.
When you remove a fragment, if addToBackStack () is not called before commit (), the fragment will be destroyed; If addToBackStack () is called, the fragment will be stopped, you can use the return key to restore data.
About the commit () method
Calling the commit () method does not immediately execute the change action contained in the transaction. The commit () method adds the transaction to the UI thread queue of the activity.
However, if necessary, you can call the executePendingTransactions () method to immediately execute the transaction provided by commit.
This is usually unnecessary unless the transaction is depended on by other threads.
Note: You can only call commit () before the activity stores its status (when the user wants to leave the activity). If you call commit () after the storage status, an exception is thrown.
This is because the status after commit is lost when the activity is restored again. If it is lost, use the commitAllowingStateLoss () method.
Instance Program
I wrote a small program and practiced fragment management. The program is not very complete. I just tried the basic usage. First, add a fragment by pressing the first button, and then replace it with the second button, the third button deletes the fragment added by the second button.
Related code:
First fragment:
ExampleFragment. java package com. example. learningfragment; import android. OS. bundle; import android. support. v4.app. fragment; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; public class ExampleFragment extends Fragment {// three methods that must be overloaded in general @ Override public void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstan CeState); System. out. println ("ExampleFragment -- onCreate");} @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {System. out. println ("ExampleFragment -- onCreateView"); return inflater. inflate (R. layout. example_fragment_layout, container, false) ;}@ Override public void onPause () {// TODO Auto-generated method stub super. onPause (); System. out. Println ("ExampleFragment -- onPause");} @ Override public void onResume () {// TODO Auto-generated method stub super. onResume (); System. out. println ("ExampleFragment -- onResume");} @ Override public void onStop () {// TODO Auto-generated method stub super. onStop (); System. out. println ("ExampleFragment -- onStop");} its layout: copy the code as follows: example_fragment_layout.xml <? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <TextView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: gravity = "left" android: textSize = "20dip" android: text = "@ string/fragment1"/> <TextView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "@ string/num1"/> <TextView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "@ string/num2"/> </LinearLayout>
Second fragment:
NewFragment. java package com. example. learningfragment; import android. OS. bundle; import android. support. v4.app. fragment; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; public class NewFragment extends Fragment {// three methods that must be overloaded in general @ Override public void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); System. out. println ("NewFragment -- onCreate");} @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {System. out. println ("NewFragment -- onCreateView"); return inflater. inflate (R. layout. new_fragment_layout, container, false) ;}@ Override public void onPause () {// TODO Auto-generated method stub super. onPause (); System. out. println ("NewFragment -- OnPause ") ;}} copy the Code as follows: new_fragment_layout.xml <? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <TextView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: textSize = "20dip" android: gravity = "left" android: text = "@ string/fragment2"/> <TextView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "@ string/num3"/> <TextView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "@ string/num4"/> </LinearLayout>
Main Activity:
LearnFragment. java package com. example. learningfragment; import android. OS. bundle; import android. support. v4.app. fragmentActivity; import android. support. v4.app. fragmentManager; import android. support. v4.app. fragmentTransaction; import android. view. view; import android. widget. button; public class extends FragmentActivity {Button btn1; Button btn2; Button btn3; Response fragmentE; NewFragment fragmentN; FragmentManager fragmentManager; @ Override public void onCreate (Bundle entity) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_learn_fragment); findViews (); setListeners (); // get fragmentManager = getSupportFragmentManager ();} private void findViews () {btn1 = (Button) findViewById (R. id. btn1); btn2 = (Button) findViewById (R. id. btn2); btn3 = (Button) findViewById (R. id. btn3);} private void setListeners () {// Add an ExampleFragment btn1.setOnClickListener (new Button. onClickListener () {public void onClick (View v) {// Add ExampleFragment fragmentE = new ExampleFragment () to the program; FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction (); fragmentTransaction. add (R. id. linear1, fragmentE); fragmentTransaction. addToBackStack (null); fragmentTransaction. commit () ;}}); // the second Button, replacing the added fragment btn2.setOnClickListener (new Button. onClickListener () {public void onClick (View v) {fragmentN = new NewFragment (); FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction (); fragmentTransaction. replace (R. id. linear1, fragmentN); fragmentTransaction. addToBackStack (null); fragmentTransaction. commit () ;}}); // the third Button to remove fragment btn3.setOnClickListener (new Button. onClickListener () {public void onClick (View v) {FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction (); fragmentTransaction. remove (fragmentN); fragmentTransaction. addToBackStack (null); fragmentTransaction. commit ();}});}}
activity_learn_fragment.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linear1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dip" android:gravity="center_horizontal" android:text="@string/layout1" /> <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btn1" /> <fragment android:name="com.example.learningfragment.ExampleFragment" android:id="@+id/fragment1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btn2" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linear2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dip" android:gravity="center_horizontal" android:text="@string/layout2" /> <Button android:id="@+id/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btn3" /> </LinearLayout> </LinearLayout>
strings.xml <resources> <string name="app_name">LearningFragment</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_learn_fragment">LearnFragment</string> <string name="layout1">LinearLayout1</string> <string name="layout2">LinearLayout2</string> <string name="fragment1">FragmentType1</string> <string name="fragment2">FragmentType2</string> <string name="num1">NO.1</string> <string name="num2">NO.2</string> <string name="num3">NO.3</string> <string name="num4">NO.4</string> <string name="btn1">Add fragment</string> <string name="btn2">Replace fragment</string> <string name="btn3">Remove fragment</string> </resources>
References:
API Guides: Fragments
Http://developer.android.com/guide/components/fragments.html
FragmentManager class documents:
Http://developer.android.com/reference/android/app/FragmentManager.html
FragmentTransaction class document
Http://developer.android.com/reference/android/app/FragmentTransaction.html
This article