static loading and dynamic loading instances of fragment in Android application development _android

Source: Internet
Author: User

1, static use of fragment
fragment is part of the UI of the activity, embedded in the activity, where multiple fragment can divide an activity into parts, which are used more in a large-screen cell phone or a tablet computer, This way, you don't have to use more than one activity to switch to such trouble. Of course fragment also can not show, only in the background to deal with some data, this article will not talk about this for the time being. Here's how to statically add fragment to the activity's layout file.

Custom fragment are usually inherited fragment this class, there are some special inheritance listfragment,dialogfragment, etc. Inheriting fragment classes typically implements three methods: OnCreate (), Oncreateview (), OnPause ();

I defined two fragment in the activity, one on the left side of the leftfragment and one on the right rightfragment. Here's the code: first we have to implement our own fragment class

Leftfragment class:

 public class Leftfragment extends Fragment {@Override public void onCreate (Bundle s
    Avedinstancestate) {super.oncreate (savedinstancestate);
  System.out.println ("Leftfragment onCreate");
    @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
    System.out.println ("Leftfragment oncreateview"); The first parameter is the layout of the interface that this fragment will display, the second is the activity that this fragment belongs to, and the third parameter determines whether the fragment is attached to the activity return Inflater.inflate (
  R.layout.leftfragment, container, true);
    @Override public void Onresume () {super.onresume ();
  System.out.println ("Leftfragment onresume");
    @Override public void OnPause () {super.onpause ();
  System.out.println ("Leftfragment onpause");
    @Override public void OnStop () {super.onstop ();
  System.out.println ("Leftfragment onStop"); }
}

There are several callback functions implemented here, primarily to see the relationship between activity and fragment lifecycle. where the Oncreateview () method returns the layout of this fragment to the activity's layout, Let the activity load. The first parameter in the Inflater.inflate (R.layout.leftfragment, container, True) method R.layout.leftfragment is the corresponding layout file ID for this fragment. The second parameter container is the target activity to insert, and the third parameter determines whether the fragment is attached to the container.
Leftfragment the corresponding layout file:

 <?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: Background= "@android: Color/holo_orange_dark"
   android:orientation= "vertical" >
 
   <button
 android : id= "@+id/previous_button"
     android:layout_width= "fill_parent"
     android:layout_height= "Wrap_content"
     android:text= "@string/previous_button"/>
 
   <button
 android:id= "@+id/next_button
     " Android:layout_width= "Fill_parent"
     android:layout_height= "wrap_content"
     android:text= "@string/next_ Button "/>

   <button
 android:id=" @+id/exit_button "
     android:layout_width=" "Fill_parent" android:layout_height= "Wrap_content"
     android:text= "@string/exit_button"/>
 
 </LinearLayout>

Rightfragment class: Similar to Leftfragment

public class Rightfragment extends Fragment
 {
   @Override public
   void OnCreate (Bundle savedinstancestate)
   {
     super.oncreate (savedinstancestate);
     System.out.println ("Rightfragment onCreate");
   }
   
   @Override public
   View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate)
   {
     System.out.println ("Rightfragment oncreateview");
     Return Inflater.inflate (R.layout.rightfragment, container, true);
  }
  
   @Override public
   void Onresume ()
  {
    super.onresume ();
     System.out.println ("Rightfragment onresume");
   }
   
   @Override public
   void OnPause ()
   {
     super.onpause ();
     System.out.println ("Rightfragment onpause");
  }
   
   @Override public
   void OnStop ()
   {
     super.onstop ();
     System.out.println ("Rightfragment onStop");
   }
 

Rightfragment the corresponding layout file:

<?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:o" rientation= "vertical" >
 
   <textview
 android:id= "@+id/show_message" android:layout_width= "Fill_"
     Parent "
     android:layout_height=" fill_parent "
     android:background=" @android: Color/holo_blue_dark "
     android:text= "@string/show_message"/>
 
 </LinearLayout>

Finally, the activity's layout file:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
 "http://schemas.android.com/apk/" Res/android " 
   android:layout_width=" fill_parent " 
   android:layout_height=" fill_parent " 
   android:o" rientation= "Horizontal" > 
  
   <fragment 
 android:id= "@+id/left_fragment" 
     Com.sunflower.LeftFragment " 
     android:layout_width=" match_parent " 
     android:layout_height=" Fill_parent " 
     android:layout_weight= "3"/> 
  
   <fragment 
 android:id= "@+id/right_fragment" 
     android:name = "Com.sunflower.RightFragment" 
     android:layout_width= "match_parent" 
     android:layout_height= "Fill_ Parent " 
     android:layout_weight=" 1 "/> 
  
</LinearLayout> 

Add the fragment tag to the layout file in the activity where the Android:name attribute corresponds to the full name of the custom fragment class, and the system will specify the fragment Oncreateview () according to the call. method to get the layout of this fragment and then join the activity. The container parameter in the Oncreateview () method is passed over at this time.
Look at the display results:

Life cycle Displays when you open a program:

The life cycle displays when you press the return key:

2. Use fragment dynamically

The simplest way to use fragment has been demonstrated, and here's how to dynamically add, update, and delete fragment.

First, the mainactivity layout file activity_main.xml The top of the file layout file is a titlefragment, which is a static declaration of fragment.

The middle is also a fragment, but this fragment is used dynamically.

The bottom is four buttons. Include an external layout file with the include tag in.

 <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.TitleFr Agment "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_alignparentbot Tom= "true" layout= "@layout/bottombar"/> <framelayout android:id= "@+id/id_content" Android:layout_wid Th= "Fill_parent" android:layout_height= "fill_parent" android:layout_above= "@id/id_ly_bottombar" android:layout _below= "@id/id_fragment_title"/> </RelativeLayout> 

The

is then the Mainactivity.java file. The most important code file in our demo is to load the above layout file through Setcontentview (). Then through Setdefaultfragment (), the default contentfragment dynamically loaded. The next step is to switch fragment dynamically through the four buttons we prevent at the bottom. This is why the fragment will have such a fire reason ~ ~ ~ ~ ~ ~ ^^

public class Mainactivity extends Actionbaractivity implements Onclicklistener {private ImageButton mtabweixin;
  Private ImageButton mtabfriend;
  Private ImageButton mtabdiscover;

  Private ImageButton MTABME;
  Private Contentfragment mweixinfragment;

  Private Friendfragment mfriendfragment;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Requestwindowfeature (Window.feature_no_title);

    Setcontentview (R.layout.activity_main);
  Initview ();
    The public void Initview () {///initializes the control and declares the event Mtabweixin = (ImageButton) Findviewbyid (r.id.weixin);
    Mtabfriend = (ImageButton) Findviewbyid (r.id.friend);
    Mtabweixin.setonclicklistener (this);

    Mtabfriend.setonclicklistener (this);
  Set the default fragment Setdefaultfragment ();
    @SuppressLint ("Newapi") private void Setdefaultfragment () {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 ();
    Open fragment transaction Fragmenttransaction transaction = Fm.begintransaction (); Switch (V.getid ()) {case R.id.weixin:if (mweixinfragment = = null) {mweixinfragment = new CONTENTFRAGM
      ENT ();
      ////Use the current fragment layout instead of the Id_content control Transaction.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
    }//Transaction.addtobackstack ();
  Transaction submitted to Transaction.commit ();

 }
}

From the above code, we can see that we can use Fragmentmanager to fragment dynamic loading, here Use the Replace method ~ ~ ~ In the next section we will introduce the fragmentmanager of the common API .... ^^

Note: If you use a android3.0 version, you need to introduce a V4 package, then the activity inherits Fragmentactivity, and then the Fragmentmanager object is obtained by Getsupportfragmentmanager () , it is recommended to change the USES-SDK minsdkversion and targetsdkversion of menifest files to more than 11, so that you do not have to introduce V4 packages.

In the middle of the code there are two dynamically loaded fragment, this and static use of fragment is the same way, write a class to inherit fragment, and then set the corresponding layout, due to the relationship between time, I only wrote two fragment here, Now post these two code pages:

The first fragment and his corresponding layout file:

public class Contentfragment extends Fragment {
  @Override public 
  View Oncreateview (Layoutinflater inflater, ViewGroup container, 
      Bundle savedinstancestate) 
  {return 
    inflater.inflate (r.layout.fragment_content, container, False); 
  } 

<?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:o" rientation= "vertical" > 
 
  <textview 
    android:layout_width= "Fill_parent" 
    Fill_parent " 
    android:gravity=" center " 
    android:text=" Weixin " 
    android:textsize=" 20sp " 
    android: textstyle= "Bold"/> 
 
</LinearLayout> 


The second fragment and his corresponding layout file:

public class Friendfragment extends Fragment {
  @Override public 
  View Oncreateview (Layoutinflater inflater, ViewGroup container, 
      Bundle savedinstancestate) 
  {return 
    inflater.inflate (r.layout.fragment_friend , container, False); 
  } 


<?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:o" rientation= "vertical" > 
 
  <textview 
    android:layout_width= "Fill_parent" 
    Fill_parent " 
    android:gravity=" center " 
    android:text=" friend " 
    android:textsize=" 20sp " 
    android: textstyle= "Bold"/> 
 
</LinearLayout> 

OK, now the basic code has, we put the demo run map posted to share with you (note: Time reason, did not pay attention to the layout and the image of landscaping, just the realization of the function), which is clicked on the following first and second button effect chart, In order to achieve the middle with a fragment dynamic loading of these two fragment display.

PS: For the simplicity of the code, do not add a button click changes or anything, mainly explain the function ~ ~ ~

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.