Two ways to create fragment in Android

Source: Internet
Author: User

Fragment is a behavior or part of the user interface in activity. You can combine multiple fragment into a multi-region UI on a single activity and can be reused in multiple activity. You can think of fragment as a module part of activity that has its own life cycle, receives its own input events, and can be added or deleted while the activity is running.

Two concepts: Fragment, Host

The life cycle of a fragment is directly affected by the life cycle of its host activity. For example, once the activity is paused, all of its fragment are also suspended, and once the activity is destroyed, all of its fragment are destroyed.

Android introduces 7fragment concept in version 3.0 (11)

With fragment, you don't have to manage the complex changes in the view architecture. By splitting the layout of actjvjty into several fragment, you can edit the rendering of the activity at run time, and those changes will be stored in the background stack managed by the activity.

To create a fragment, you must create a subclass of fragment (or a subclass that inherits from it). The code for the Fragment class looks much like activity. It has the same callback functions as the activity, such as OnCreate (), OnStart (), OnPause (), and OnStop (). In fact, if you're using a ready-made Android app instead of fragment, you can simply port the code from the activity's callback function to the respective fragment callback function.

In addition to the base class fragment, here are a few subclasses you might inherit:

Dialogfragment, Listfragment, preferencefragment

In general, you need to implement at least some of the following life cycle methods:

onCreate (): This method is called by the system when the fragment is created. In the implementation code, you can initialize the necessary components that you want to keep in fragment, and re-enable them when the fragment is paused or stopped.

Oncreateview (): This method is called by the system the first time the user interface is drawn for fragment. To draw the user interface for fragment, this function must return the painted
Out of the fragment's root view. If fragment does not have a user interface, you can return empty.

onPause (): The function is called as the first omen of the user leaving fragment (although this does not always mean that fragment is destroyed). Before the end of the current user session, it is common to commit any changes that should persist here (because the user may no longer return).

Here are two ways to add fragment to your activity: (1) declare fragment (2) in the activity layout file and add fragment to the saved ViewGroup with Java code

The demo example is as follows:

The two colors differentiate between two different fragment:

(1) Declare fragment in the activity layout file

Now we can display the results by declaring the two fragment in the layout file activity_main.xml.

First step: Create a layout file Left_layout.xml (right_layout.xml) file on the left (right) in layout:
1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <linearlayout xmlns:android= " Android "3     android:orientation=" vertical "android:layout_width=" match_parent "4     android:layout_height=" Match_parent "5     android:gravity=" Center_horizontal "6     android:background=" #6f6669 "> 7     <button 8         android:id= "@+id/panhouye" 9         android:layout_width= "Wrap_content"         android:layout_height= Content "One         android:text=" pan hou ye "/>12     <button13         android:id=" @+id/bikonghai "         android: Layout_width= "Wrap_content"         android:layout_height= "wrap_content" android:text= Blue Sky         "/>17 </" Linearlayout>

Step Two: Build the Java class ( that corresponds to the Left_layout.xml (right_layout.xml) layout for the inherited fragment file:

1 Import; 2 Import Android.os.Bundle; 3 Import Android.view.LayoutInflater; 4 Import Android.view.View; 5 Import Android.view.ViewGroup; 6/** 7  * Created by Panchengjia on 2016/12/15.8  */9 public class Leftfragment extends Fragment {     @Overrid E11 public     void OnCreate (Bundle savedinstancestate) {         super.oncreate (savedinstancestate);     }14     @Override15 public     View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {16< c10/>//to get the corresponding layout from the layout fill in the parameters.         View View =inflater.inflate (R.layout.left_layout,container,false)         view;19     }20     @Override21 public     void OnPause () {         super.onpause ();     }24}
Step three: Layout in the main layout file Activity_main.xml declaration of the left and right two fragment layouts
 1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <linearlayout xmlns:android= " /res/android "3 xmlns:tools=" Http:// "4 android:id=" @+id/activity_main "5 Android:lay Out_width= "Match_parent" 6 android:layout_height= "match_parent" 7 android:orientation= "Horizontal" 8 Tools:con         text= "Com.example.administrator.fragmenttest.MainActivity" > 9 <fragment10 android:layout_width= "0DP" 11 android:layout_height= "Match_parent" android:layout_weight= "1" android:name= "Com.example.admini Strator.fragmenttest.LeftFragment "tools:layout=" @layout/left_layout "/>15 <fragment16 Android : layout_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "3" android:n Ame= "Com.example.administrator.fragmenttest.RightFragment" tools:layout= "@layout/right_layout"/>21 </lin Earlayout> 

(2) Add fragment to the saved ViewGroup with Java code

Here we demonstrate adding the fragment (Right_layout.xml) on the right side to the main layout viewgroup via Java code.

The knowledge points used to add fragment through code are summarized as follows:

To manage fragment in your activity, you can use Fragmentmanager. can be obtained by calling Getfragmentmanager () in the activity. Using Fragmentmanager, you can do the following things, including:

1. Using Findfragmentbyld () (for fragment that provide an interface in the activity layout) or Fjndfragmentbytag () to get the fragment that exist in the activity (for fragment that have an interface or no interface).

2. Eject the fragment from the background stack using Popbackstack () (imitating the user's back command).

3. Use Addonbackstackchangedlistener () to register a listener that listens for changes in the background stack.

A major feature of using fragment in activity is the ability to add, delete, replace, and perform other actions in response to user interaction. Each series of changes submitted to the activity is called a transaction and can be processed using APIs in Fragmenttransactjon.

The knowledge points used here are labeled in the code, and you can learn more about extension usage by looking at the API documentation.

The first step: The main layout file in Layout activity_main2.xml file (the left fragment layout is declared directly in the layout, the right fragment is populated with code to framelayout implementation):
 1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <linearlayout xmlns:android= " /res/android "3 xmlns:tools=" Http:// "4 android:id=" @+id/activity_main "5 Android:lay Out_width= "Match_parent" 6 android:layout_height= "match_parent" 7 android:orientation= "Horizontal" 8 Tools:con         text= "Com.example.administrator.testfragment.MainActivity" > 9 <fragment10 android:id= "@+id/left" 11         Android:layout_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "1" 14     Android:name= "Com.example.administrator.testfragment.LeftFragment" tools:layout= "@layout/left_layout"/>16 <framelayout17 android:id= "@+id/right" android:layout_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "3" ></framelayout>21 </linearlayout> 

Step Two: The of the main layout in Java is added to the main layout ViewGroup by code fragment:
 1 Import; 2 Import; 3 Import; 4 Import Android.os.Bundle;     5 public class Main2activity extends Appcompatactivity {6//Declare Java Class 7 Fragmentmanager Fragmentmanager used in this session; 8 Fragmenttransaction fragmenttransaction; 9 rightfragment rightfragment;10 @Override11 protected void onCreate (Bundle savedinstancestate) {su Per.oncreate (Savedinstancestate), Setcontentview (r.layout.activity_main2), 14/* In the activity corresponding Java class through Getfra Gmentmanager () 15 * Get Fragmentmanager for managing fragment16 in Viewgrop * */17 Fragmentmanager=getfragmentman          Ager ();/*fragmentmanager to manage fragment (add, replace, and other execution actions) 19 * A series of transaction changes that need to be performed by Fragmenttransaction to operate 20 */21 fragmenttransaction = Fragmentmanager.begintransaction (); 22//Instantiate the fragment23 Rightfragme to be managed NT = new Rightfragment (); 24//Add the fragment to the correspondingLayout in Fragmenttransaction.add (,rightfragment); 26//Transaction completion required to submit Fragmenttransaction.commi T (); 28}29}

It's here today, the interaction between the fragmen and the activity. We'll go back to bed early.

Two ways to create fragment in Android

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: 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.