Explain the two ways to create fragment in Android _android

Source: Internet
Author: User
Tags commit

Fragment is an act or a part of the user interface in an activity. You can combine multiple fragment into a multiple-area UI on a single activity, and can be reused in multiple activity. You can think of fragment as a modular part of the activity, which has its own lifecycle, receives its own input events, and can be added or deleted as it runs.

Two concepts: Fragment, Host

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

Android introduces 7fragment concept in 3.0 (11) Versions

With fragment, you may not have to manage the complex changes in the view system. By dividing the layout of the actjvjty into several fragment, you can edit the presentation 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 fragment subclass (or inherit from its subclass). The code for the Fragment class looks like an 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 application instead of fragment, you can simply migrate the code from the activity's callback function to its own 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 several 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 fragment is paused or stopped.
    • Oncreateview (): This method is called the first time the user interface is drawn for fragment. To draw the user interface for fragment, this function must return the root view of the fragment that is plotted. If fragment does not have a user interface, it can return null.
    • OnPause (): The system calls this function as the user's first warning to leave 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 be persisted here (since the user may no longer return).

Here are two ways to add fragment to an activity:

(1) Declare fragment in the activity layout file

(2) Adding fragment to an existing ViewGroup through Java code

The demo example is as follows:

The two colors distinguish between two different fragment:

(1) Declare fragment in the activity layout file

Now we can implement the display by declaring two fragment in the Layout master layout file Activity_main.xml.

First step: Create the Left (right) layout file Left_layout.xml (right_layout.xml) file in layout:

 <?xml version= "." Encoding= "utf-"?> <linearlayout xmlns:android=
 "http://schemas.android.com/apk/res/ Android "
   android:orientation=" vertical "android:layout_width=" match_parent "
   android:layout_height=" Match_parent "
   android:gravity=" center_horizontal "
   android:background=" #f ">
   <button
     Android:layout_width= "Wrap_content"
     android:layout_height= "wrap_content"
     android:text= "pan hou ye"/>
   <button
     android:layout_width= "wrap_content"
     android:layout_height= "Wrap_content"
     android: text= "Azure Sea"/>
 </LinearLayout>

Step two: Establish a left_layout.xml (right_layout.xml) layout corresponding to the inherited Fragment Java class Leftfragment.java (Rightfragment.java)

Leftfragment.java file:

 Import android.app.Fragment;
 Import Android.os.Bundle;
 Import Android.view.LayoutInflater;
 Import Android.view.View;
 Import Android.view.ViewGroup;
 /**
  * Created by Panchengjia on//.
  *
 /public class Leftfragment extends Fragment {
   @Override public
   void OnCreate (Bundle savedinstancestate) {
     super.oncreate (savedinstancestate);
   }
   @Override public
   View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
     //To get the corresponding layout
     through the layout fill in the parameter View View =inflater.inflate (R.layout.left_layout,container,false);
     return view;
   }
   @Override public
   void OnPause () {
     super.onpause ();
   }
 }

Step three: Declare the left and right two fragment layouts in the main layout file Activity_main.xml in Layout

<?xml version= "." Encoding= "utf-"?> <linearlayout xmlns:android=
 "http://schemas.android.com/apk/res/ Android "
   xmlns:tools=" Http://schemas.android.com/tools "
   android:id=" @+id/activity_main "
   android: Layout_width= "Match_parent"
   android:layout_height= "match_parent"
   android:orientation= "Horizontal
   " tools:context= "Com.example.administrator.fragmenttest.MainActivity" >
   <fragment
     android:layout_ Width= "DP"
     android:layout_height= "match_parent"
     android:layout_weight= "
     android:name=" Com.example.administrator.fragmenttest.LeftFragment "
     tools:layout=" @layout/left_layout "/>
   < Fragment
     android:layout_width= "DP"
     android:layout_height= "match_parent"
     android:layout_weight= " "
     android:name=" com.example.administrator.fragmenttest.RightFragment "
     tools:layout=" @layout/right_ Layout "/>
 </LinearLayout>

(2) Adding fragment to an existing ViewGroup through Java code

Here we demonstrate adding fragment (Right_layout.xml) from 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 an activity, you can use Fragmentmanager. can be obtained by calling Getfragmentmanager () in the activity. Using Fragmentmanager can do the following things, including:

1. Use of Findfragmentbyld () (used to provide an interface fragment in the activity layout) or Fjndfragmentbytag () to obtain the fragment that exists in the activity (for fragment with interfaces or no interfaces).

2. Use Popbackstack () (imitate the user's back command) to eject fragment from the background stack.

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 handled using APIs in Fragmenttransactjon.

The knowledge points used here will be annotated in the code, and you can see the extended usage in detail by looking at the API documentation.

Step one: Layout The main layout file Activity_main2.xml file (the left fragment layout is declared directly in the layout, and the right fragment is populated by code to the Framelayout implementation):

 <?xml version= "." Encoding= "utf-"?> <linearlayout xmlns:android=
 "http://schemas.android.com/apk/res/ Android "
   xmlns:tools=" Http://schemas.android.com/tools "
   android:id=" @+id/activity_main "
   android: Layout_width= "Match_parent"
   android:layout_height= "match_parent"
   android:orientation= "Horizontal
   " tools:context= "Com.example.administrator.fragmenttest.MainActivity" >
   <fragment
     android:layout_ Width= "DP"
     android:layout_height= "match_parent"
     android:layout_weight= "
     android:name=" Com.example.administrator.fragmenttest.LeftFragment "
     tools:layout=" @layout/left_layout "/>
   < Framelayout
     android:id= "@+id/right"
     android:layout_width= "DP"
     android:layout_height= "Match_" Parent "
     android:layout_weight=" ></FrameLayout>
 </LinearLayout>

Step two: Main2activity.java of the main layout in Java Add fragment to the main layout viewgroup by code:

 Import Android.app.FragmentManager;
 Import android.app.FragmentTransaction;
 Import android.support.v.app.appcompatactivity;
 Import Android.os.Bundle;
   The public class Mainactivity extends Appcompatactivity {//Declares the Java class used to Fragmentmanager Fragmentmanager;
   Fragmenttransaction fragmenttransaction;
   Rightfragment rightfragment;
     @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
     Setcontentview (R.layout.activity_main); /* Obtain Fragmentmanager in the activity corresponding Java class through Getfragmentmanager () * for managing Fragment * */Fragmentmanager=ge in Viewgrop
     Tfragmentmanager ();  /*fragmentmanager to manage a series of transaction changes in fragment (add, replace, and other execution actions), it is necessary to operate through fragmenttransaction/fragmenttransaction
     = Fragmentmanager.begintransaction ();
     Instantiate the Fragment rightfragment = new Rightfragment () to be managed;
     Add fragment to the corresponding layout by adding (transaction processing) Fragmenttransaction.add (r.id.right,rightfragment); The transaction needs to be submitted fragmenttrAnsaction.commit ();

 }
 }

The

Is here today, the interaction between the fragmen and the activity we'll go back to bed early.

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.