Android fragment dynamic creation details and sample code
Android fragment dynamic creation
Fragment is a part or a behavior in the interface of an activity. Multiple fragments can be combined into one activity to create a multi interface, and one fragment can be reused in multiple activities. An activity that can modularize the fragment task. It has its own life cycle, receives its own events, and can be added or deleted when the activity runs.
A fragment cannot exist independently. It must be embedded into an activity, and its life cycle is directly affected by the activity in which it is located. For example, when an activity is suspended, all its fragments are suspended. When an activity is destroyed, all its fragments are destroyed. However, when the activity runs (after onresume() and before onpause()), you can manipulate each fragment individually, such as adding or deleting them. When the above transactions for fragments are executed, transactions can be added to a stack, which is managed by activity, and each item in the stack is a fragment transaction. With this stack, fragment transactions can be executed in reverse, so that the "back" key (backward navigation) can be supported at the fragment level.
When adding a fragment to an activity, it must be placed in the ViewGroup control, and the fragment's own interface needs to be defined. You can declare fragment in the layout.xml layout file. The elements are: < fragment >; You can also create a fragment in your code and add it to the ViewGroup control. However, the fragment does not have to be placed in the interface of the activity. It can be hidden in the background to work for the activity.
Let's fight
Project layout file code:
Then create two new fragment.xml files under the layout folder
fragment1.xml:
fragment2.xml
Then create two new java files in the project source folder
Fragment1.java
Fragment2.java
Run project
Next, implement the dynamic creation of fragments
Create a new project based on the previous project. Delete the original activity_ The code segments of fragment1 and fragment2 in the main.xml code remain unchanged
Next, add the following code in mainactivity:
The above code realizes the display of different fragments when the mobile phone faces different directions
Thank you for reading, hope to help you, thank you for your support to this site!