Simple usage of Android Fragment (fragmentation)

Source: Internet
Author: User

1. What is a fragment?

Fragmentation (Fragment) is a UI fragment that can be embedded in an activity, which allows the program to make more reasonable and full use of the space on the large screen, so it is widely used on the tablet. Although fragmentation should be a whole new concept for you, I believe you should learn effortlessly, because it is so much like activity that it can also contain layouts and have its own life cycle. You can even think of fragmentation as a mini-activity, although this mini-activity is likely to be as big as normal activity.

So how do you use fragmentation to make the most of your flat screen space? Imagine that we are developing a news app, where one interface uses the ListView to display the title of a set of news, and when one of the headings is clicked, a different screen opens to show the details of the news. If you're designing on a phone, we can put a list of news headlines in one activity and put the details of the news in another activity, as shown in 1.

Figure 1

However, if this is also the case on the tablet, then the headline list will be stretched to fill the entire flat screen, and the headline of the news will not be too long, which would result in a large number of blank areas on the interface, 2 shown.

Figure 2

Therefore, a better design is to put the news headlines list interface and the news detail interface in two fragments, and then introduce the two fragments in the same activity, so that the screen space can be fully utilized, 3.

Figure 3

2. How to use fragments

Create a new Fragmenttest project and start our Debris Discovery Tour.

Create a New Left fragment layout left_fragment.xml, as shown in the following code:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >        <ButtonAndroid:id= "@+id/button"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_horizontal"Android:text= "button"        />    </LinearLayout>

This layout is very simple, just place a button and let it be centered horizontally. Then create a new right fragment layout right_fragment.xml, as shown in the code below:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:background= "#00ff00"android:orientation= "vertical" >        <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_horizontal"android:textsize= "20SP"Android:text= " This was right fragment"        />    </LinearLayout>

As you can see, we set the background color of this layout to green and placed a textview for displaying a piece of text. Then create a new Leftfragment class that inherits from fragment. Note that there may be two different packages under the Fragment for you to choose from, it is recommended to use Android.app.Fragment, because our program is for Android 4.0 above the system, The fragment under the other package is primarily for compatibility with low-version Android systems. The code for Leftfragment is as follows:

 Public class extends Fragment {    @Override    public  View oncreateview (layoutinflater inflater, ViewGroup Container,            Bundle savedinstancestate) {        false);         return view;    }}

This is simply a rewrite of the Fragment Oncreateview () method, and then, in this method, the Left_fragment layout just defined is dynamically loaded through the Layoutinflater inflate () method, and the whole method is straightforward. Then we use the same method to create a new rightfragment, the code is as follows:

 Public class extends Fragment {    @Override    public  View oncreateview (layoutinflater inflater, ViewGroup Container,            Bundle savedinstancestate) {        false);         return view;    }}

To create a new another_right_fragment.xml, the code looks like this:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:background= "#ffff00"android:orientation= "vertical" >        <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_horizontal"android:textsize= "20SP"Android:text= "This was another right fragment"        />    </LinearLayout>

The code for this layout file is basically the same as the code in Right_fragment.xml, except that the background color is changed to yellow, and the displayed text is changed. Then create a new anotherrightfragment as a second right fragment, as shown in the following code:

 Public class extends Fragment {        @Override    public  View oncreateview (layoutinflater inflater, ViewGroup Container,            Bundle savedinstancestate) {        false);         return view;    }    }

The code is also very simple, and the another_right_fragment layout you just created is loaded in the Oncreateview () method. So we're ready for another fragment, and then we'll look at how to add it dynamically to the activity. To modify the Activity_main.xml, the code looks like this:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent">
<!--static load fragment---<FragmentAndroid:id= "@+id/left_fragment"Android:name= "Com.example.fragmenttest.LeftFragment"Android:layout_width= "0DP"Android:layout_height= "Match_parent"Android:layout_weight= "1" /> <FramelayoutAndroid:id= "@+id/right_layout"Android:layout_width= "0DP"Android:layout_height= "Match_parent"Android:layout_weight= "1" >
<!--can be dynamically loaded in this container fragment--
 <  fragment  android:id  = "@+id/right_fragment"   and Roid:name  = "Com.example.fragmenttest.RightFragment"   Android:layout_width  = "Match_parent"   Android:layout_height  = "Match_parent"  />  </ framelayout  >  </ linearlayout  >  

As you can see, the right fragment is now placed in a framelayout, which is the simplest layout in Android, it doesn't have any positioning, and all the controls are placed in the upper-left corner of the layout. Since it only requires a fragment in the layout, it is ideal for using framelayout.

We will then replace the contents of the Framelayout in the code, enabling the ability to dynamically add fragmentation. Modify the code in the mainactivity as follows:

 Public classMainactivityextendsActivityImplementsOnclicklistener {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button Button=(Button) Findviewbyid (R.id.button); Button.setonclicklistener ( This); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.button:anotherrightfragment Fragment=Newanotherrightfragment (); Fragmentmanager Fragmentmanager=Getfragmentmanager (); Fragmenttransaction Transaction=Fragmentmanager. BeginTransaction ();            Transaction.replace (r.id.right_layout, fragment);            Transaction.commit ();  Break; default:             Break; }    }}

As you can see, we first register a click event for the button in the left fragment and then put the dynamic add fragment logic in the Click event. The combination of code shows that the dynamic addition of fragments is divided into 5 main steps.

    1. Creates a fragment instance to be added.
    2. Gets to Fragmentmanager, which can be directly called by the Getfragmentmanager () method in the activity.
    3. Opens a transaction, which is opened by calling the BeginTransaction () method.
    4. Adding fragments to a container, typically implemented using the Replace () method, requires the ID of the incoming container and the fragment instance to be added.
    5. Commit the transaction and call the Commit () method to complete.

This completes the dynamic addition of fragments in the activity of the function, run the program, you can see the boot interface 4, and then click the button, Effect 5 is shown.

Figure 4

Figure 5

3. Simulate the return stack in fragments

We have successfully implemented the ability to add fragments dynamically to the activity, but when you try it you will find that by clicking on the button you add a fragment, and then pressing the back key will exit directly. If we want to imitate the effect similar to the return stack, press the back key to return to the previous fragment.

In fact, it is very simple, Fragmenttransaction provides a addtobackstack () method that can be used to add a transaction to the return stack, modifying the code in Mainactivity as follows:

 Public classMainactivityextendsActivityImplementsOnclicklistener {... @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.button:anotherrightfragment Fragment=Newanotherrightfragment (); Fragmentmanager Fragmentmanager=Getfragmentmanager (); Fragmenttransaction Transaction=Fragmentmanager. BeginTransaction ();            Transaction.replace (r.id.right_layout, fragment); Transaction.addtobackstack ( NULL);            Transaction.commit ();  Break; default:             Break; }    }}

Here we call the Addtobackstack () method of Fragmenttransaction before the transaction commits, it can receive a name to describe the state of the return stack, and generally pass in null. Now rerun the program, and click on the button to add anotherrightfragment to the activity, and then press the back key, you will find that the program does not exit, but return to the Rightfragment interface, the Next button will be pressed again to exit.

4. Communication between fragments and activities

Although fragments are embedded in the activity, they are not so intimately related. As you can see, fragments and activities exist in separate classes, and there is no obvious way to communicate directly. What if you want to invoke the method in the fragment in the activity, or invoke the method in the activity in the fragment?

To facilitate communication between fragments and activities, Fragmentmanager provides a method similar to Findviewbyid () that is specifically used to get fragments from the layout file, as shown in the following code:

Rightfragment rightfragment = (rightfragment) Getfragmentmanager (). Findfragmentbyid (r.id.right_fragment);

Call Fragmentmanager's Findfragmentbyid () method to get an instance of the corresponding fragment in the activity, and then make it easy to invoke the method in the fragment.

How do you call the method in the fragment in the activity, and how do you invoke the method in the activity in the fragment? In fact, this is even easier, in each fragment you can call the Getactivity () method to get the activity instance associated with the current fragment, as shown in the following code:

Mainactivity activity = (mainactivity) getactivity ();

Once you have an activity instance, it is easy to invoke the method in the fragment in the activity. Also, you can use the Getactivity () method when you need to use a context object in a fragment, because the activity you get is a context object in itself.

At this time do not know whether you have a question in mind, since the communication between debris and activity has been solved, then can the fragments and fragments between the communication?

To be honest, this problem does not seem complex, its basic idea is very simple, first in a fragment can get the activity associated with it, and then through this activity to get another instance of the fragment, so that the different fragments of the communication function, so here our answer is yes.

Simple usage of Android Fragment (fragmentation)

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.