Use Fragment to control switching between multiple pages based on Android

Source: Internet
Author: User

Android has provided various Demo examples for Fragment. The API Demo below our SDK contains various use examples for Fragment. You need to check the Demo, you can simply look at the API Demo program without looking for it everywhere. Different functions are separated to implement different classes.

Today, I will explain how to control Fragment, mainly by switching views and page replacement. There is also how to get the Fragment management object and the communication mode with the Activity.

1. Manage Fragment
To manage fragment in an activity, you must use FragmentManager to obtain its instance by calling getFragmentManager () of the activity.

• You can do something through FragmentManager, including using findFragmentById () (fragment for providing a UI in activity layout) or findFragmentByTag () (applicable to fragment with or without a UI) obtain the fragment in the activity.
• Pop up fragment from the background stack and use popBackStack () (simulate the user to press the BACK command ).
• Use addOnBackStackChangeListener () to register a listener that listens to background stack changes.

2. Handling Fragment transactions
A strong feature of using fragment in an activity is to add, remove, replace, and execute fragment based on user interaction. Each set of changes committed to the activity is called a transaction and can be processed using the API in FragmentTransaction. We can also save every transaction to a backstack managed by activity, allowing users to navigate back through the change in fragment (similar to navigation back through activity ).

Get a FragmentTransaction instance from FragmentManager:

Copy codeThe Code is as follows:
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction ();


Each transaction is a set of changes to be executed at the same time. You can set all the changes you want to execute in a given transaction, such as add (), remove (), and replace (). Then, to apply the transaction to the activity, you must call commit ().

Before calling commit (), you may want to call addToBackStack () to add the transaction to the backstack of a fragment transaction. This back stack is managed by the activity and allows the user to return to the previous fragment status by pressing the BACK button.

Copy codeThe Code is as follows:
// Create and modify an instance
Fragment newFragment = newExampleFragment ();
FragmentTransaction transaction = getFragmentManager (). beginTransaction ();
// Replace whatever is in thefragment_container view with this fragment,
// And add the transaction to the backstack
Transaction. replace (R. id. fragment_container, newFragment );
Transaction. addToBackStack (null );
// Submit the modification
Transaction. commit ();


The above is how to replace one fragment with another and retain the previous state in the background stack. In this example, newFragment replaces the fragment identified by R. id. fragment_container in the current layout container. By calling addToBackStack (), the replace transaction is saved to the back stack. Therefore, you can roll BACK the transaction and press the back button to bring BACK the previous fragment.

If you add multiple changes to a transaction (such as add () or remove () and call addToBackStack (), then you call commit () all previous application changes will be added to the background stack as a single transaction, and the BACK button will roll them BACK together. The order of adding changes to FragmentTransaction is not important, except for the following:

• You must call commit ()
• If multiple fragment entries are added to the same container, the order in which they are added determines the order they are displayed in view hierarchy.

If addToBackStack () is not called when a transaction is executed to remove fragment, the fragment will be destroyed after the transaction is committed, and the user cannot navigate back to it. In this case, if addToBackStack () is called when a fragment is removed, the fragment will be stopped. If the user returns the navigation, the fragment will be restored. In addition, for each fragment transaction, you can apply a transaction animation by calling setTransition () before committing the transaction.

Calling commit () does not execute transactions immediately. On the contrary, it schedules transactions. Once prepared, it runs on the UI thread of the activity (main thread ). If necessary, you can call executePendingTransactions () from your UI thread to immediately execute the transactions committed by commit. But this is usually not necessary unless the transaction is a slave of the tasks in other threads.
Warning:You can only use commit () to submit transactions before the activity saves its status (when the user leaves the activity.
 
3. Communicate with Activity
Fragment is implemented as an Activity-independent object and can be used in multiple activities. However, a given fragment instance is directly bound to the activity containing the package. Special fragment can use getActivity () to access the Activity instance, and it is easy to execute a task such as searching for a view in activity layout. The following code:

Copy codeThe Code is as follows:
View listView = getActivity (). findViewById (R. id. list );


Similarly, the activity can obtain a reference to Fragment from FragmentManager to call the method in fragment and use findFragmentById () or findFragmentByTag ().

Copy codeThe Code is as follows:
ExampleFragment fragment = (ExampleFragment) getFragmentManager (). findFragmentById (R. id. example_fragment );


4. Summary
Finally, let's take a look at the Fragment example. The Android official team has provided various Demo examples for Fragment usage. The API Demo below our SDK contains various use examples of Fragment, A friend who needs to watch the Demo can simply look at the program of the API Demo without looking for it everywhere. Different functions are separated to implement different classes. You can view the specific code as needed.

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.