Second, the use of fragment

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/8881711

We all know that the interface display on Android is implemented through activity, activity is too often used, I believe we are already very familiar with, here will not repeat.

But activity also has its limitations, the same interface on the phone may look good, on the tablet is not necessarily, because the tablet screen is very large, the phone's interface on the tablet may be excessively stretched, the control spacing is too large, and so on. This is a better time to experience the effect of embedding "small activity" in activity, and then each "small activity" can have its own layout. Therefore, our protagonist fragment debut today.

Preliminary study on fragment

To allow the interface to be better displayed on the tablet, Android introduced the Fragment (fragmentation) feature in version 3.0, which is very similar to activity and can include layouts like activity. Fragment is usually nested in the activity, now imagine this scenario: there are two Fragment,fragment 1 contains a ListView, each line shows the title of a book. Fragment 2 contains TextView and ImageView to show the details and pictures of the book.

If the program is now running in portrait mode on a tablet or phone, Fragment 1 may be embedded in one activity, while Fragment 2 may be embedded in another activity, as shown in:

And if the program is now running on a flat screen mode, two fragment can be embedded in the same activity as shown:

As you can see, using fragment allows us to make the most of our tablet's screen space, and here we explore how to use fragment.

The first thing to note is that fragment was introduced in version 3.0, and if you are using a system before 3.0, you need to import the ANDROID-SUPPORT-V4 jar package before you can use the fragment feature.

Create a new project called Fragments, and then create a new layout file named Fragment1.xml under the Layout folder:

[HTML] view plain copy

    1. <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
    2. Android:layout_width= "Match_parent"
    3. android:layout_height= "Match_parent"
    4. android:background= "#00ff00" >
    5. <textview
    6. Android:layout_width= "Wrap_content"
    7. android:layout_height= "Wrap_content"
    8. Android:text= "This is fragment 1"
    9. Android:textcolor= "#000000"
    10. Android:textsize= "25SP"/>
    11. </LinearLayout>

As you can see, this layout file is very simple and there is only one linearlayout, which adds a textview. We create a new fragment2.xml:

[HTML] view plain copy

    1. <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
    2. Android:layout_width= "Match_parent"
    3. android:layout_height= "Match_parent"
    4. android:background= "#ffff00" >
    5. <textview
    6. Android:layout_width= "Wrap_content"
    7. android:layout_height= "Wrap_content"
    8. Android:text= "This is Fragment 2"
    9. Android:textcolor= "#000000"
    10. Android:textsize= "25SP"/>
    11. </LinearLayout>

Then create a new class Fragment1, this class is inherited from the fragment:

[Java] view plain copy

    1. public class Fragment1 extends Fragment {
    2. @Override
    3. Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
    4. Return Inflater.inflate (R.layout.fragment1, container, false);
    5. }
    6. }

As we can see, this class is also very simple, mostly loading the fragment1.xml layout file we just wrote and returning it. In the same way, we'll write the Fragment2 again:

[Java] view plain copy

    1. public class Fragment2 extends Fragment {
    2. @Override
    3. Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
    4. Return Inflater.inflate (R.layout.fragment2, container, false);
    5. }
    6. }

Then open or create a new activity_main.xml as the main activity layout file, add two fragment references, use the Android:name prefix to refer to the specific fragment:

[HTML] view plain copy

    1. <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
    2. Android:layout_width= "Match_parent"
    3. android:layout_height= "Match_parent"
    4. Android:baselinealigned= "false" >
    5. <fragment
    6. Android:id= "@+id/fragment1"
    7. Android:name= "Com.example.fragmentdemo.Fragment1"
    8. Android:layout_width= "0dip"
    9. android:layout_height= "Match_parent"
    10. android:layout_weight= "1"/>
    11. <fragment
    12. Android:id= "@+id/fragment2"
    13. Android:name= "Com.example.fragmentdemo.Fragment2"
    14. Android:layout_width= "0dip"
    15. android:layout_height= "Match_parent"
    16. android:layout_weight= "1"/>
    17. </LinearLayout>

Finally open or new mainactivity as the main activity of the program, the code inside is very simple, are automatically generated:

[Java] view plain copy

    1. public class Mainactivity extends Activity {
    2. @Override
    3. protected void OnCreate (Bundle savedinstancestate) {
    4. Super.oncreate (savedinstancestate);
    5. Setcontentview (R.layout.activity_main);
    6. }
    7. }

Now let's run the program once, and we'll see that an activity contains two fragment, two fragment split the entire screen, as follows:

Add fragment Dynamically

You've learned how to use fragment in XML, but this is just the simplest feature of fragment. The real strength of fragment is that it can be dynamically added to the activity, so that's what you have to master. When you learn to add fragment to the activity while the program is running, the interface of the program can be customized more varied. Now we'll see how to add fragment dynamically.

Or on the basis of the previous section of the code to modify, open activity_ Main.xml, the reference to fragment is deleted, only the outermost linearlayout is preserved, and an ID is added to it, because we want to add fragment dynamically, without adding it in the XML, the following code is removed:

[HTML] view plain copy

    1. <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
    2. Android:id= "@+id/main_layout"
    3. Android:layout_width= "Match_parent"
    4. android:layout_height= "Match_parent"
    5. Android:baselinealigned= "false" >
    6. </LinearLayout>

Then open mainactivity and modify the code as follows:

[Java] view plain copy

  1. public class Mainactivity extends Activity {
  2. @Override
  3. protected void OnCreate (Bundle savedinstancestate) {
  4. Super.oncreate (savedinstancestate);
  5. Setcontentview (R.layout.activity_main);
  6. Display display = Getwindowmanager (). Getdefaultdisplay ();
  7. if (Display.getwidth () > Display.getheight ()) {
  8. Fragment1 fragment1 = new Fragment1 ();
  9. Getfragmentmanager (). BeginTransaction (). replace (R.id.main_layout, fragment1). commit ();
  10. } else {
  11. Fragment2 Fragment2 = new Fragment2 ();
  12. Getfragmentmanager (). BeginTransaction (). replace (R.id.main_layout, Fragment2). commit ();
  13. }
  14. }
  15. }

First, we want to get the width and height of the screen, and then judge if the screen width is greater than the height of the add fragment1, if the height is greater than the width of the add Fragment2. Dynamically adding fragment is divided into 4 main steps:

1. Access to Fragmentmanager, which can be obtained directly through Getfragmentmanager in the activity.

2. Open a transaction by calling the BeginTransaction method.

3. Adding fragment to the container, typically implemented with the Replace method, requires passing in the ID of the container and an instance of fragment.

4. Commit the transaction and invoke the Commit method commit.

Now run the program with the effect as shown:

If you are running with the emulator, press CTRL + F11 to switch to portrait mode. The effect is as follows:

The life cycle of fragment

Like activity, fragment has its own life cycle, it is important to understand the life cycle of fragment, and we look at how the life cycle of fragment is based on code:

[Java] view plain copy

  1. public class Fragment1 extends Fragment {
  2. public static final String TAG = "Fragment1";
  3. @Override
  4. Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
  5. LOG.D (TAG, "Oncreateview");
  6. Return Inflater.inflate (R.layout.fragment1, container, false);
  7. }
  8. @Override
  9. public void Onattach (activity activity) {
  10. Super.onattach (activity);
  11. LOG.D (TAG, "Onattach");
  12. }
  13. @Override
  14. public void OnCreate (Bundle savedinstancestate) {
  15. Super.oncreate (savedinstancestate);
  16. LOG.D (TAG, "onCreate");
  17. }
  18. @Override
  19. public void onactivitycreated (Bundle savedinstancestate) {
  20. Super.onactivitycreated (savedinstancestate);
  21. LOG.D (TAG, "onactivitycreated");
  22. }
  23. @Override
  24. public void OnStart () {
  25. Super.onstart ();
  26. LOG.D (TAG, "OnStart");
  27. }
  28. @Override
  29. public void Onresume () {
  30. Super.onresume ();
  31. LOG.D (TAG, "Onresume");
  32. }
  33. @Override
  34. public void OnPause () {
  35. Super.onpause ();
  36. LOG.D (TAG, "onPause");
  37. }
  38. @Override
  39. public void OnStop () {
  40. Super.onstop ();
  41. LOG.D (TAG, "onStop");
  42. }
  43. @Override
  44. public void Ondestroyview () {
  45. Super.ondestroyview ();
  46. LOG.D (TAG, "Ondestroyview");
  47. }
  48. @Override
  49. public void OnDestroy () {
  50. Super.ondestroy ();
  51. LOG.D (TAG, "OnDestroy");
  52. }
  53. @Override
  54. public void Ondetach () {
  55. Super.ondetach ();
  56. LOG.D (TAG, "Ondetach");
  57. }
  58. }

As you can see, the above code prints the log in every life cycle method, and then we run the program and see the print log as follows:

At this point, click the Home button, print the log as follows:

If you re-enter the program again, print the log as follows:

Then click the Back button to exit the program, print the log as follows:

Seeing here, I believe most of my friends are very clear, because it is too similar to the life cycle of the activity. There are only a few new methods that are not available in the activity, so here are some highlights:

    • Onattach method: Called when fragment is associated with an activity.
    • Oncreateview method: Called when the layout is loaded for fragment.
    • Onactivitycreated method: Called when the OnCreate method in the activity finishes executing.
    • Ondestroyview method: Called when the layout in the fragment is removed.
    • Ondetach method: Called when fragment and activity are disassociate.

Communication between the fragment

Typically, the activity will contain multiple fragment, so how to communicate between multiple fragment is a very important issue. Let's look at an example of how to access another fragment view in one fragment.

Or on the basis of the first section of the code to modify, first open fragment2.xml, in this layout to add a button:

[HTML] view plain copy

    1. <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
    2. Android:layout_width= "Match_parent"
    3. android:layout_height= "Match_parent"
    4. android:orientation= "Vertical"
    5. android:background= "#ffff00" >
    6. <textview
    7. Android:layout_width= "Wrap_content"
    8. android:layout_height= "Wrap_content"
    9. Android:text= "This is Fragment 2"
    10. Android:textcolor= "#000000"
    11. Android:textsize= "25SP"/>
    12. <button
    13. Android:id= "@+id/button"
    14. Android:layout_width= "Wrap_content"
    15. android:layout_height= "Wrap_content"
    16. android:text= "Get fragment1 text"
    17. />
    18. </LinearLayout>

Then open Fragment1.xml and add an ID for TextView:

[HTML] view plain copy

    1. <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
    2. Android:layout_width= "Match_parent"
    3. android:layout_height= "Match_parent"
    4. android:background= "#00ff00" >
    5. <textview
    6. Android:id= "@+id/fragment1_text"
    7. Android:layout_width= "Wrap_content"
    8. android:layout_height= "Wrap_content"
    9. Android:text= "This is fragment 1"
    10. Android:textcolor= "#000000"
    11. Android:textsize= "25SP"/>
    12. </LinearLayout>

Then open Fragment2.java, add the Onactivitycreated method, and handle the button's Click event:

[Java] view plain copy

  1. public class Fragment2 extends Fragment {
  2. @Override
  3. Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
  4. Return Inflater.inflate (R.layout.fragment2, container, false);
  5. }
  6. @Override
  7. public void onactivitycreated (Bundle savedinstancestate) {
  8. Super.onactivitycreated (savedinstancestate);
  9. Button button = (button) getactivity (). Findviewbyid (R.id.button);
  10. Button.setonclicklistener (New Onclicklistener () {
  11. @Override
  12. public void OnClick (View v) {
  13. TextView TextView = (TextView) getactivity (). Findviewbyid (R.id.fragment1_text);
  14. Toast.maketext (Getactivity (), Textview.gettext (), Toast.length_long). Show ();
  15. }
  16. });
  17. }
  18. }

Now run the program and click on the button on the Fragment2, as shown in the results:

We can see that the view in Fragment1 was successfully obtained in Fragment2 and the toast was popped. How is this going to be achieved? Mainly through the Getactivity this method is implemented. The Getactivity method allows fragment to obtain the associated activity and then invoke the Findviewbyid method of the activity to obtain a view of the other fragment associated with the activity.

Well, that's all you need to know about fragment. If you want to experience the actual combat of fragment, please continue to read the Android phone tablet, using fragment to achieve compatible mobile phone and tablet programs and Android fragment application combat, use fragments to say goodbye to Activitygroup.

First time to get blog update reminders, as well as more technical information sharing, welcome to follow my public number, sweep the QR code below or search number Guolin_blog, you can pay attention to.

Second, the use of fragment

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.