Android Fragment analysis, androidfragment

Source: Internet
Author: User

Android Fragment analysis, androidfragment

1. How is Fragment Generated? 2. What is Fragment?

Android runs on a variety of devices, including cell phones with small screens, ultra-large screen tablets, and even TVs. For the screen size gap, in many cases, a set of apps are first developed for mobile phones, then a copy is copied, and the layout is modified to adapt to the tablet Shenma super screen. Can't an App adapt to mobile phones and tablets at the same time? Of course, yes. Fragment is designed to solve this problem. You can regard Fragment as an integral part of an Activity's interface. Even the Activity's interface can have completely different Fragment components, what's more handsome is that Fragment has its own lifecycle and receives and processes user events, so that it does not have to write a bunch of control event processing code in the Activity. More importantly, you can dynamically add, replace, and remove a Fragment.

3. Fragment Lifecycle

Fragment must exist in dependency and Activity. Therefore, the lifecycle of an Activity directly affects the lifecycle of Fragment. The figure on the official website shows the relationship between the two lifecycles:

We can see that Fragment has several additional lifecycle callback methods than Activity:
OnAttach (Activity)
Called when Fragment is associated with Activity.
OnCreateView (LayoutInflater, ViewGroup, Bundle)
Create a view for this Fragment
OnActivityCreated (Bundle)
Called when the onCreate method of the Activity returns
OnDestoryView ()
Corresponds to onCreateView, called when the Fragment view is removed
OnDetach ()
Corresponds to onAttach. It is called when the association between Fragment and Activity is canceled.
Note: Except onCreateView, If you overwrite all other methods, you must call the implementation of this method by the parent class.

4. How to Use Fragment statically and dynamically

Static usage:

This is the simplest way to use Fragment. You can use Fragment as a common control and directly write it in the layout file of the Activity. Steps:

 

1. inherit Fragment and rewrite onCreateView to determine Fragemnt Layout

2. Declare the Fragment in the Activity, just like the normal View.

The following is an example (I use 2 Fragment as the layout of the Activity, one Fragment for the title layout, and one Fragment FOR THE CONTENT layout ):

Layout file of TitleFragment:

TitleFragment:

Similarly, the layout file of ContentFragment is as follows:

MainActivity:

Activity layout file: FragmentManager is used to dynamically load Fragment. Note: If you use versions earlier than Android, You need to introduce v4 packages, and then the Activity inherits FragmentActivity, then get the FragmentManager through getsuppfrfragmentmanager. However, we recommend that the minSdkVersion and targetSdkVersion of the uses-sdk of the Menifest file be changed to 11 or above, so that you do not need to introduce the v4 package.

Describes the common APIs of FragmentManager in detail:

Three Common Fragment classes:

 

Android. app. Fragment is mainly used to define Fragment

Android. app. FragmentManager is mainly used to operate Fragment in an Activity.

Android. app. FragmentTransaction ensures the atomicity of Fragment operations on some columns

 

A. method for obtaining FragmentManage:

GetFragmentManager () // v4, getSupportFragmentManager

B. The main operations are the FragmentTransaction methods.

FragmentTransaction transaction = fm. benginTransatcion (); // start a transaction

Transaction. add ()

Add a Fragment to the Activity

Transaction. remove ()

Remove a Fragment from the Activity. If the removed Fragment is not added to the rollback stack (this will be detailed later), the Fragment instance will be destroyed.

Transaction. replace ()

Replacing the current one with another Fragment is actually a combination of remove () and add ~

Transaction. hide ()

Hiding the current Fragment is only invisible and will not be destroyed.

Transaction. show ()

Show Hidden Fragment

Detach ()

The view is removed from the UI. Unlike remove (), the fragment status is maintained by FragmentManager.

Attach ()

Re-create the view, attach it to the UI, and display it.

Transatcion. commit () // submit a transaction

Note: Fragment buddies often encounter errors such as inconsistent Activity states: State loss. The main reason is that the commit method must be called before Activity. onSaveInstance.

The above is basically all the methods used to operate Fragment. You can add, remove, or replace multiple operations when a transaction is started to commit.

It is worth noting that if you like to use Fragment, you must know which of these methods will destroy the view, which will destroy the instance, and which is only hidden to better use them.

A. For example, I have filled in some data in EditText in FragmentA. When switching to FragmentB, if you want to see the data in A, it is suitable for hide and show. That is to say, if you want to keep the panel for user operations, you can use hide and show. Of course, do not try to make a non-null judgment on the new instance.

B. For example, if I do not want to retain user operations, you can use remove (), add (), or replace (), which has the same effect as remove and add.

C. There is a slight difference between remove and detach. If Stack rollback is not considered, remove will destroy the entire Fragment instance, while detach only destroys its view structure, the instance will not be destroyed. How can we choose between them? If your current Activity persists, you can use detach first if you do not want to retain user operations.

The above describes some of the methods commonly used in Fragment. I believe that after reading this article, you will be clear about the reasons for Fragment and how to use Fragment. You can also understand it based on the API explanation, I once thought that Fragment had some problems with column disorder, but it was because I didn't figure out its lifecycle.

5. Fragment rollback Stack

Similar to the Android system that maintains a task stack for the Activity, we can also maintain a rollback stack for the Activity to save the changes in each Fragment transaction. If you add the Fragment task to the rollback stack, When you click the back button, you will see the last saved Fragment. Once Fragment pops up completely from the back stack, the user clicks the back key again to exit the current Activity.

 

 

Click the first button, switch to the second interface, click the second button, switch to the third interface, and then click Back. This is not like the Activity jump when I was a beginner in Android. Of course, it is definitely not here, or I will kneel down. Here is the implementation of Fragment. When you click Back, the Fragment rollback stack keeps popping up.

 

How to add a Fragment transaction to the rollback Stack:

FragmentTransaction. addToBackStack (String)

The code below: it is obvious that there are three Fragment and one Activity in total.

First look at the layout file of the Activity:

MainActivity. java

Simply add FragmentOne to FrameLayout in the layout file. Note that FragmentTransaction. addToBackStack (String) is not called here, because I do not like to click Back to display the whiteboard when it is currently displayed. Instead, the corresponding Back key is used to exit our Activity.

 

Below is the FragmentOne

We used the replace method when clicking the button in FragmentOne. If you read the previous blog, remember that replace is the combination of remove and add, and if you do not add transactions to the rollback stack, the previous Fragment instance will be destroyed. Obviously, we call tx. addToBackStack (null); adds the current transaction to the rollback stack, so the FragmentOne instance will not be destroyed, but the view level will still be destroyed, that is, onDestoryView and onCreateView will be called. The evidence is: take a closer look at the content we entered in the text box before the jump, and it disappeared when the user returned the first interface.

 

Next, FragmentTwo

When we click here, we do not use replace, but first hide the current Fragment, then add the FragmentThree instance, and finally add the transaction to the rollback stack. The purpose of this solution is to provide you with a solution: if you do not want to redraw the view, please take a closer look at the content we entered in the EditText of FragmentTwo, when the user returns, the data is still ~~~

 

Finally, FragmentThree is a simple Toast:

Well, after the above introduction, we should already know what the Fragment rollback stack is like and the scenarios of hide, replace, and other applications.

 

Note: The overall code above does not have any reference value. to display the rollback stack, the code above will be reconstructed after Fragment communicates with the Activity!

 

2. Fragment communicates with Activity

Because all Fragment is attached to the Activity, the communication is not complex. It is generally summarized:

A. If your Activity contains a reference to your managed Fragment, you can directly access the public methods of all Fragment by referencing

B. If no reference to Fragment is saved in the Activity, it does not matter. Each Fragment has a unique TAG or ID. You can use getFragmentManager. findFragmentByTag () or findFragmentById () to obtain any Fragment instance, and then perform the operation.

C. In Fragment, you can get the instance of the currently bound Activity through getActivity, and then perform the operation.

NOTE: If Context is required in Fragment, call getActivity (). If the Context still exists after the Activity is destroyed, use getActivity (). getApplicationContext ().

3. Best practices for communication between Fragment and Activity

Because the reuse of Fragment must be considered, the coupling between Fragment and Activity must be reduced, and Fragment should not be directly operated on other Fragment. After all, the Fragment operation should be determined by its manager Activity.

The following code is used to refactor the click events of FragmentOne and FragmentTwo, and the response of the Activity to the click events:

First, let's look at FragmentOne:

We can see that FragmentOne is not coupled with any Activity, and any Activity can be used. We declare an interface to call its click event back and forth, the Activity that you want to manage click events can implement this interface. We can see that in onClick, we first determine whether the current bound Activity has implemented this interface, and if so, call it.

 

Let's look at FragmentTwo.

It is very similar to FragmentOne, But we provide methods such as setListener, which means that the Activity not only needs to implement this interface, but also must call mFTwo. setfTwoBtnClickListener (this ).

 

Finally, let's look at Activity:

6. Fragment transaction;

7. And some special uses of Fragment, such as: What is the use of Fragment without layout?

8. How does Fragment interact with the Activity?

9. How to Create a dialog box for Fragment?

10. How does Fragment integrate with ActionBar.

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.