Android manages fragments in an Activity

Source: Internet
Author: User

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: Copy codeThe Code is 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.Copy codeThe Code is as follows: // 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:Copy codeThe Code is as follows: 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 reloaded
@ Override
Public void onCreate (Bundle savedInstanceState)
{
// TODO Auto-generated method stub
Super. onCreate (savedInstanceState );
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 codeThe Code is 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:Copy codeThe Code is as follows: 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 reloaded
@ 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 codeThe Code is 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:Copy codeThe Code is as follows: 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 LearnFragment extends FragmentActivity
{
Button btn1;
Button btn2;
Button btn3;
ExampleFragment fragmentE;
NewFragment fragmentN;
FragmentManager fragmentManager;
@ Override
Public void onCreate (Bundle savedInstanceState)
{
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_learn_fragment );
FindViews ();
SetListeners ();
// Get the object of the class required for Fragment Management
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 button
Btn1.setOnClickListener (new Button. OnClickListener ()
{
Public void onClick (View v)
{
// Add ExampleFragment to the program
FragmentE = new ExampleFragment ();
FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction ();
FragmentTransaction. add (R. id. linear1, fragmentE );
FragmentTransaction. addToBackStack (null );
FragmentTransaction. commit ();
}
}
);
// The second button, replacing the added fragment with a NewFragment
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 ();
}
}
);
}
}

Copy codeThe Code is as follows: 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>

Resources:Copy codeThe Code is as follows: 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>

Program running:

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.