search
HomeJavajavaTutorialAndroid basics: using Fragment to control switching between multiple pages

Today I will explain the control of Fragment, mainly operations such as switching View and page replacement. There is also how to obtain the management object of Fragment and how to communicate with Activity.

1. Managing Fragments
To manage fragments in an activity, you need to use FragmentManager. Get its instance by calling getFragmentManager() of the activity.

•You can do some things through FragmentManager, Including: Use findFragmentById() (used to provide a UI fragment in the activity layout) or findFragmentByTag() (applicable to fragments with or without UI) to obtain the fragment that exists in the activity.
•Pop the fragment from the back stack, using popBackStack() (simulating the user pressing the BACK command).
•Use addOnBackStackChangeListener() to register a listener that listens to changes in the back stack.

2. Processing Fragment transactions
A very strong feature of using fragments in activities is: adding, removing, replacing, and performing other actions on fragments based on the user's interaction. Each set of changes submitted to an activity is called a transaction and can be handled using the API in FragmentTransaction. We can also save each transaction to an activity-managed backstack, allowing the user to navigate back through changes in the fragment (similar to navigating back through the activity).

Obtain a FragmentTransaction instance from FragmentManager:

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 perform within a given transaction, using methods such as add(), remove(), and replace(). Then, to apply the transaction to the activity, commit() must be called.

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 state by pressing the BACK button.

//创建修改实例
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);
//提交修改
transaction.commit();

The above is how to replace one fragment with another and keep the previous state in the back 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, so the user can roll back the transaction and bring back the previous fragment by pressing the BACK button.


If you add multiple changes to a transaction (such as add() or remove()) and call addToBackStack(), then all of the changes applied before you call commit() Changes will be added to the back stack as a single transaction, and pressing the BACK button will roll them back together. The order in which changes are added to the FragmentTransaction is not important, with the following exceptions:

•Must call commit() last
•If multiple fragments are added to the same container, the order in which they are added determines their placement in the view hierarchy The order shown in

When executing a transaction that removes a fragment, if addToBackStack() is not called, that fragment will be destroyed when the transaction commits, and the user cannot navigate back to it. For this reason, when removing a fragment, if addToBackStack() is called, the fragment will be stopped, and if the user navigates back, it will be resumed. Additionally, for each fragment transaction, you can apply a transaction animation by calling setTransition() before committing the transaction.

Calling commit() does not execute the transaction immediately. On the contrary, it schedules the transaction and, once ready, runs it on the activity's UI thread (the main thread). If necessary, however, you can call executePendingTransactions() from your UI thread to immediately execute the transaction submitted by commit(). But this is usually not necessary unless the transaction is a slave of a task in another thread.
Warning: You can only use commit() to commit a transaction before the activity saves its state (when the user leaves the activity).

3. Communicate with Activity
Although Fragment is implemented as an independent Activity object and can be used in multiple activities, but a given fragment instance is directly bound to the activity that contains it. Special fragments can access the Activity instance using getActivity() and easily perform tasks such as finding a view in the activity layout. As in the following code:

View listView =getActivity().findViewById(R.id.list);

Similarly, the activity can call methods in the fragment by obtaining a reference to the Fragment from the FragmentManager, using findFragmentById() or findFragmentByTag().

ExampleFragment fragment =(ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);

4. Summary
Finally, I need to talk about examples of Fragment. Android officials have provided Demo examples of various uses of Fragment. The API Demo under our SDK contains various examples of Fragment. For usage examples, if you need to see the demo, just look at the API Demo program without having to look around. Different functions are separated and different classes are implemented. You can view the specific code as needed.

For more Android basics and related articles on using Fragment control to switch multiple pages, please pay attention to the PHP Chinese website!
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools