Android Fragment in-depth analysis

Source: Internet
Author: User

Android Fragment in-depth analysis
People who have had some experience in the interview will have a deep understanding. In each interview, they will generally ask about Fragment. 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 is running on a variety of devices, including cell phones with small screens, tablets with ultra-large screens, 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's lifecycle Fragment must be dependent on the Activity, so the Activity's lifecycle will directly affect the Fragment's lifecycle. The figure on the official website shows the relationship between the two: Fragment has several additional lifecycle callback functions than Activity: onAttach (Activity ); // call onCreateView (LayoutInflater, ViewGroup, Bundle) when the Activity is associated with Fragment; // create onActivityCreate (bundle) for the Fragment view; // onCreate () for the Activity (); onDestoryView () is called when the method returns; // corresponds to onCreateView, and onDetach () is called when the modified Fragment is removed; // corresponds to onAttach, when the association between Fragment and Activity is canceled, call Note: Except onCreateView, If you override all other methods, you must call the implementation of this method by the parent class. 3. Use Fragment in static mode. Next, it's time to use Fragment. 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. Step: 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 ). TitleFragment layout file. here we can see that we can separate the layout in each Fragment: copy the Code <? Xml version = "1.0" encoding = "UTF-8"?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "45dp" android: background = "@ drawable/title_bar"> <ImageButton android: id = "@ + id/id_title_left_btn" android: layout_width = "wrap_content" android: layout_height = "fill_parent" android: layout_centerVertical = "true" android: background = "@ drawable/showleft_selector"/> <TextView Android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: gravity = "center" android: text = "I'm not" android: textColor = "# fff" android: textSize = "20sp" android: textStyle = "bold"/> </RelativeLayout> copy the code 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. Copy the public class TitleFragment extends Fragment {private ImageButton mButton; @ Override ("NewApi") @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle identifier) {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 ;}} copy the code. Similarly, there is also the ContentFragment layout file content_fragment.xml copy Code <? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <TextView android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: gravity = "center" android: text = "Use the Fragment console" android: textSize = "20sp" android: textStyle = "bold"/> </LinearLayout> the same code is copied as ContentFrag. Ment. java File Replication code public class ContentFragment extends Fragment {@ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater. inflate (R. layout. content_fragment, container, false) ;}} copy the main Activity and its layout file MainActivity. java File Replication code public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {Super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_main) ;}} copy the code activity_main.xml file. here we can see that Fragment is used in xml files just like a common control. Copy the Code <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" tools: context = "com. example. staticfragment. mainActivity "> <fragment android: name =" com. example. staticfragment. titleFragment "android: id =" @ + id/title "android: layout_height =" 45dp "android: layout_width =" ma Tch_parent "/> <fragment android: layout_below =" @ id/title "android: name =" com. example. staticfragment. contentFragment "android: id =" @ + id/content "android: layout_height =" fill_parent "android: layout_width =" fill_parent "/> </RelativeLayout>: 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 simplest method of using Fragment has been demonstrated above. 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. Copy the Code <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent"> <fragment android: id = "@ + id/id_fragment_title" android: name = "com. example. dynamicfragment. titleFragment "android: layout_width =" fill_parent "android: layout_height =" 45dp "/> <include android: id =" @ + id/id _ Ly_bottombar "android: layout_width =" fill_parent "android: layout_height =" 55dp "android: layout_alignParentBottom =" true "layout =" @ layout/bottombar "/> <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"/> </RelativeLayout> copy the code and 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 ~~~ ^ Copy the public class MainActivity extends ActionBarActivity implements OnClickListener {private ImageButton listener; private ImageButton mTabFriend; private ImageButton mTabDiscover; private ImageButton mTabMe; private ContentFragment listener; private temporary listener; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); request WindowFeature (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); // sets the default Fragment setDefaultFragment ();} @ SuppressLint ("NewApi") private void setDefa UltFragment () {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 (); // enable 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;} // transac Tion. addToBackStack (); // transaction commit transaction. commit () ;}} copy the code from the above Code. 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 paste the two code pages: The first Fragment and its corresponding layout file: copy the public class ContentFragment extends Fragment {@ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater. inflate (R. layout. fragment_content, container, false) ;}} copy the Code <? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <TextView android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: gravity = "center" android: text = "weixin" android: textSize = "20sp" android: textStyle = "bold"/> </LinearLayout> copy the second Fragment of the Code and its corresponding layout file: Copy the public class FriendFragment extends Fragment {@ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater. inflate (R. layout. fragment_friend, container, false) ;}} copy the Code <? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <TextView android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: gravity = "center" android: text = "friend" android: textSize = "20sp" android: textStyle = "bold"/> </LinearLayout> the code has been copied. Now all the basic code is available. (Note: for the reason of time, do not pay attention to the layout and beautification of the image, but only implement the function). Click the first and second buttons below, respectively, in this way, a Fragment is used in the middle to dynamically load the display of the two Fragment.

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.