Android learning-in-depth analysis of Android Fragment
People who have some experience in the interview have a deep understanding. Fragment knowledge is usually asked during each interview. So today I will share Fragment with you separately.
How Fragment is generated, what is Fragment, Fragment lifecycle, static and dynamic use of Fragment, Fragment rollback stack, Fragment transactions, and some special uses of Fragment, such: what is the usefulness of Fragment without layout? How does Fragment interact with Activiy? How does Fragment create a dialog box? How to integrate Fragment with ActionBar...
1. Generation and introduction of 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, and then a copy is copied to modify the layout to adapt to the super screen. Can't an app adapt to both mobile phones and tablets? The answer is, of course, the original intention of Fragment. Fragment is to solve this problem.
You can regard Fragment as part of an Activity interface, and even the Activity interface is composed of totally different Fragment. What's more handsome is that Fragment has its own declaration cycle and receives and processes user events, in this way, you do not need to write a bunch of event and control code in an Activity. More importantly, you can dynamically add, replace, and remove a Fragment.
2. Fragment Lifecycle
Fragment must be dependent on the Activity. Therefore, the lifecycle of the Activity directly affects the lifecycle of the Fragment. The figure on the official website shows the relationship between the two:
We can see that Fragment has several additional lifecycle callback functions than Activity:
OnAttach (Activity); // called when Activity is associated with Fragment
OnCreateView (LayoutInflater, ViewGroup, Bundle); // create the Fragment View
OnActivityCreate (bundle); // called when the onCreate (); method of the Activity returns
OnDestoryView (); // corresponds to onCreateView. It is called when the modified Fragment 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 the parent class for this method.
3. Static Fragment
Next, it's time to practice it. Pay attention to it and start to write code ~~~~
This is the simplest way to use Fragment. You can use Fragment as a normal control and directly write it in the layout file of the Activity. You can call Fragment with the layout file.
Steps:
1. inherit Fragment, and rewrite onCreateView to determine the Fragment layout.
2. Declare the Fragment in the Activity, just like the normal View.
The following is an example (I use two Fragment as the layout of the Activity, one Fragment for the title layout, and one Fragment FOR THE CONTENT layout ).
The layout file of TitleFragment. here we can see that we can separate the layout in each Fragment:
TitleFragment. java files. here we can see that they can perform independent initialization space in each Fragment and process events such as buttons, reducing the burden on the Activity, there is no need to write a large amount of code to initialize controls and event responses in the Activity, which makes our code look more concise and readable.
public class TitleFragment extends Fragment { private ImageButton mButton; @SuppressLint("NewApi") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.title_fragment, container, false); mButton = (ImageButton)view.findViewById(R.id.id_title_left_btn); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "i am an ImageButton in TitleFragment ! ", Toast.LENGTH_SHORT).show(); } }); return view; }}
Similarly, the ContentFragment layout file content_fragment.xml
Likewise, the ContentFragment. java File
public class ContentFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.content_fragment, container,false); }}
The following figure shows the main Activity and its layout file.
MainActivity. java File
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); }}
Activity_main.xml file. here we can see that Fragment is used in xml files just like a common control.
The running effect is as follows:
Note: the source code is not uploaded due to time reasons. If you need the demo source code, you can leave a message and I will send it to you separately...
4. Dynamic use of Fragment
The above demonstrates the simplest way to use Fragment. The following describes how to dynamically add, update, and delete Fragment.
The first is the layout file activity_main.xml of MainActivity. The top of the layout file is a TitleFragment, which is a static declared Fragment.
There is also a Fragment in the middle, but this Fragment is dynamically used.
There are four buttons at the bottom. Include tags to include external layout files.
<frameLayout android:id="@+id/id_content" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/id_ly_bottombar" android:layout_below="@id/id_fragment_title" />
Then, MainActivity. java file. It is also the most important code file in our demo. The first step is to load the layout File above through setContentView. then, use setdefafrfragment (); to dynamically load the default ContentFragment. The next step is to use the four buttons we prevent at the bottom to dynamically switch the Fragment at will. This is why Fragment is so popular ~~~ ^
Public class MainActivity extends ActionBarActivity implements OnClickListener {private ImageButton listener; private ImageButton mTabFriend; private ImageButton mTabDiscover; private ImageButton mTabMe; private ContentFragment listener; private FriendFragment listener; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_main); initView ();} public void initView () {// initialize the control and declare the event mTabWeixin = (ImageButton) findViewById (R. id. weixin); mTabFriend = (ImageButton) findViewById (R. id. friend); mTabWeixin. setOnClickListener (this); mTabFriend. setOnClickListener (this); // set the default Fragment setDefaultFragment ();} @ SuppressLint ("NewApi") private void setdefafrfragment () {FragmentManager manager = getFragmentManager (); fragmentTransaction transaction = manager. beginTransaction (); mWeiXinFragment = new ContentFragment (); transaction. replace (R. id. id_content, mWeiXinFragment); transaction. commit () ;}@ SuppressLint ("NewApi") @ Override public void onClick (View v) {FragmentManager fm = getFragmentManager (); // start the Fragment transaction FragmentTransaction transaction = fm. beginTransaction (); switch (v. getId () {case R. id. weixin: if (mWeiXinFragment = null) {mWeiXinFragment = new ContentFragment () ;}// use the current Fragment layout to replace the transaction control of id_content. replace (R. id. id_content, mWeiXinFragment); break; case R. id. friend: if (mFriendFragment = null) {mFriendFragment = new FriendFragment ();} transaction. replace (R. id. id_content, mFriendFragment); break;} // transaction. addToBackStack (); // transaction commit transaction. commit ();}}
From the code above, we can see that we can use FragmentManager to dynamically load Fragment. Here we use the replace method ~~~ In the next section, we will detail the common APIs of FragmentManager .... ^
NOTE: If android3.0 is used, you need to introduce the v4 package, then the Activity inherits the FragmentActivity, and then get the FragmentManager object through getsuppfrfragmentmanager, however, we recommend that you change the minSdkVersion and targetSdkVersion of the uses-sdk of the Menifest file to 11 or above, so that you do not need to introduce the v4 package.
There are two Fragment dynamically loaded in the middle of the Code. This is the same as the static method of using the ragment statement. Write a class that inherits the Fragment and set the corresponding layout, due to the time relationship, I only wrote two Fragment here. Now I can paste these two code pages:
The first Fragment and its corresponding layout file:
public class ContentFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_content, container, false); } }
The second Fragment and its corresponding layout file:
public class FriendFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_friend, container, false); } }
Now we have all the basic code. We will post the demo running diagram to share with you (Note: Due to the time, we did not pay attention to the layout and beautification of the image, is only the function implementation), this is to click the first and second buttons respectively, so as to achieve a dynamic loading of the two Fragment display in the middle.
Ps: for the sake of code conciseness, I will not add button click changes or anything. I will mainly explain the functions ~~~
5. Common Fragment APIs:
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 in some columns. You must be familiar with the term transaction ~
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 ()
Detaching this Fragment from the Activity will destroy its layout, but will not destroy the instance
Attach ()
Re-associate the Fragment separated from the Activity to the Activity and recreate its view level.
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.
Due to the length of the article, the remaining content is reserved for the next article. In the next article, we will introduce:
1. How to manage the Fragment rollback Stack
2. How Fragment interacts with Activity
3. Best practices for Fragment and Activity Interaction
4. Use of Fragment without a view
5. Create a dialog box using Fragment
6. How to integrate with ActionBar and MenuItem ~~
Original article by Meng's IT staff www.itmmd.com