An in-depth analysis of Android Fragment (above) _android

Source: Internet
Author: User

Since fragment appeared, there has been a period of time, feel that we talk about what can talk with fragment about the relationship, do anything to ask under fragment can realize not ~ ~ Ha, is not a bit over ~ ~ ~

In order for 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 an activity. Fragment is usually nested within the activity, now imagine the scene: two Fragment,fragment 1 contains a ListView, each row showing the title of a book. Fragment 2 contains TextView and ImageView to display the details and pictures of the book.

This article explains how fragment produces, what is the fragment,fragment lifecycle, how static and dynamic use of fragment,fragment fallback stack, fragment transaction, and some special uses of fragment, For example: What is the use of fragment without a layout? How does fragment interact with the activity? Fragment how do I create a dialog box? Fragment how to integrate with Actionbar and so on.

1, the production and introduction of fragment

Android runs on a variety of devices, with small-screen phones, oversized screens and even TVs. For the screen size gap, in many cases, is the first mobile phone to develop a set of apps, and then copy, modify the layout to adapt to the plate God horse super big screen. Can't it be that an app can adapt to both the phone and the tablet at the same time, of course, must have AH. Fragment's appearance is to solve such a problem. You can think of fragment as an integral part of an activity's interface, and even the interface of the activity can be composed entirely of different fragment, and the more handsome fragment has its own lifecycle and the events that receive and process the user, This eliminates the need to write a bunch of code for the event handling of the control in the activity. More importantly, you can dynamically add, replace, and remove a fragment.

2, the Fragment life cycle

Fragment must be dependent and activity, so the life cycle of activity will directly affect the life cycle of fragment. This picture of the official website illustrates the relationship between the two life cycles:

You can see that fragment has several additional lifecycle callback methods than the activity:

Onattach (activity)

Called when the fragment is associated with an activity.

Oncreateview (Layoutinflater, Viewgroup,bundle)

Create a view of this fragment

Onactivitycreated (Bundle)

Called when the OnCreate method of the activity returns

Ondestoryview ()

When the view of the fragment is removed, it is called to correspond with the Oncreateview.

Ondetach ()

Corresponds to the Onattach when the fragment is canceled when the activity association is called

Note: In addition to Oncreateview, all other methods, if you override them, must call the parent class for the implementation of the method.

3, static use of fragment

Hey, finally to the use of the moment ~ ~

This is the simplest way to use fragment, using fragment as a normal control, written directly in the activity's layout file. Steps:

1, inherit fragment, rewrite Oncreateview decide fragemnt layout

2, in the activity of the Declaration of this fragment, as the normal view

Here's an example (I use 2 fragment as the layout of the activity, a fragment for the title layout, and a fragment for the content layout):

Titlefragment Layout file:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= 
"http://schemas.android.com/apk" /res/android " 
 android:layout_width=" match_parent " 
 android:layout_height=" 45DP " 
 android:background= "@drawable/title_bar" > 
 <imagebutton 
  android:id= "@+id/id_title_left_btn" 
  android:layout_width = "Wrap_content" 
  android:layout_height= "wrap_content" 
  android:layout_centervertical= "true" 
  Android : layout_marginleft= "3DP" 
  android:background= "@drawable/showleft_selector"/> 
 <textview 
  Android:layout_width= "Fill_parent" 
  android:layout_height= "fill_parent" 
  android:gravity= "center" 
  android:text= "I am not a micro-letter" 
  android:textcolor= "#fff" 
  android:textsize= "20sp" 
  android:textstyle= " Bold "/> 
</RelativeLayout>

Titlefragment

 package com.zhy.zhy_fragments; 
Import android.app.Fragment; 
Import Android.os.Bundle; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.view.ViewGroup; 
Import Android.widget.ImageButton; 
Import Android.widget.Toast; 
 public class Titlefragment extends Fragment {private ImageButton mleftmenu; @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {V 
  Iew view = inflater.inflate (R.layout.fragment_title, container, false); 
  Mleftmenu = (ImageButton) View.findviewbyid (R.ID.ID_TITLE_LEFT_BTN); Mleftmenu.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Toast.mak 
   EText (Getactivity (), "I am a ImageButton in titlefragment!", Toast.length_short). Show (); 
  } 
  }); 
 return view; } 
} 

Similarly, there are Contentfragment's layout files:

<?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=" uses fragment Panel " 
  android:textsize= 20sp" 
  android:textstyle= "Bold"/> 

Java

Package com.zhy.zhy_fragments; 
Import android.app.Fragment; 
Import Android.os.Bundle; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.view.ViewGroup; 
public class Contentfragment extends Fragment 
{ 
 @Override public 
 View Oncreateview (layoutinflater Inflater, ViewGroup container, 
   Bundle savedinstancestate) 
 {return 
  inflater.inflate ( R.layout.fragment_content, container, false); 
 } 
 

Mainactivity

Package com.zhy.zhy_fragments; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.view.Window; 
public class Mainactivity extends activity 
{ 
 @Override 
 protected void OnCreate (Bundle Savedinstancestate) 
 { 
  super.oncreate (savedinstancestate); 
  Requestwindowfeature (window.feature_no_title); 
  Setcontentview (R.layout.activity_main); 
 } 

The layout file for the activity:

<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.zhy.zhy_fragments". Titlefragment " 
  android:layout_width=" fill_parent " 
  android:layout_height=" 45DP "/> 
 <fragment 
  android:layout_below= "@id/id_fragment_title" 
  android:id= "@+id/id_fragment_content" 
  android: Name= "Com.zhy.zhy_fragments. Contentfragment " 
  android:layout_width=" fill_parent " 
  android:layout_height=" fill_parent "/> 
" </RelativeLayout> 

Do you think of fragment as a normal view? Declared in the activity's layout file, and then all the control of the event processing code by their respective fragment to deal with the moment feel that there is a good clean wood ~ ~ Code readability, Reusability and maintainability is not an instant upgrade ~ ~ ~ below look at the effect of the picture:

4, dynamic use of fragment

As demonstrated above, the simplest way to use fragment is to describe how to dynamically add, update, and delete fragment

In order to dynamically use fragment, we modify the actvity layout file, using a framelayout in the middle, add the following four buttons ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~!

<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.zhy.zhy_fragments". Titlefragment " 
  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_alignparentbottom=" true " 
  layout=" @layout/bottombar "/> 
 <framelayout 
  android:id= "@+id/id_content" 
  android:layout_width= "fill_parent" 
  android:layout_height= "Fill_" Parent " 
  android:layout_above=" @id/id_ly_bottombar " 
  android:layout_below=" @id/id_fragment_title "/> 
</RelativeLayout>

The layout of the bottom four buttons will not be affixed, to see the effect of the picture will understand ~ ~

The following main activity

Package com.zhy.zhy_fragments; 
Import android.app.Activity; 
Import Android.app.FragmentManager; 
Import android.app.FragmentTransaction; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.view.Window; 
Import Android.widget.LinearLayout; 
 public class Mainactivity extends activity implements Onclicklistener {private LinearLayout mtabweixin; 
 Private LinearLayout mtabfriend; 
 Private Contentfragment mweixin; 
 Private Friendfragment mfriend; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
  Requestwindowfeature (Window.feature_no_title); 
  Setcontentview (R.layout.activity_main); 
  Initializes the control and declares the event Mtabweixin = (linearlayout) Findviewbyid (r.id.tab_bottom_weixin); 
  Mtabfriend = (linearlayout) Findviewbyid (r.id.tab_bottom_friend); 
  Mtabweixin.setonclicklistener (this); 
  Mtabfriend.setonclicklistener (this); 
 Set the default fragment Setdefaultfragment (); } 
 private void Setdefaultfragment () {Fragmentmanager fm = Getfragmentmanager (); 
  Fragmenttransaction transaction = Fm.begintransaction (); 
  Mweixin = new Contentfragment (); 
  Transaction.replace (R.id.id_content, mweixin); 
 Transaction.commit (); 
  @Override public void OnClick (View v) {Fragmentmanager fm = Getfragmentmanager (); 
  Open fragment transaction Fragmenttransaction transaction = Fm.begintransaction (); Switch (V.getid ()) {case R.id.tab_bottom_weixin:if (mweixin = = null) {mweixin = new contentfragment ( 
   ); 
   ////Use the current fragment layout instead of the Id_content control Transaction.replace (R.id.id_content, mweixin); 
  Break 
   Case R.id.tab_bottom_friend:if (mfriend = = null) {mfriend = new friendfragment (); 
   } transaction.replace (R.id.id_content, mfriend); 
  Break 
  }//Transaction.addtobackstack (); 
 Transaction submitted to Transaction.commit (); } 
}

We can see that we are using Fragmentmanager to dynamically load the fragment, here is the Replace method ~ ~ In the next section I will detail the common API of Fragmentmanager.

Note: If you use the following version of Android3.0, you need to introduce the V4 package, then the activity inherits the Fragmentactivity, then Getsupportfragmentmanager gets fragmentmanager. However, the proposed version of the Menifest file Uses-sdk minsdkversion and targetsdkversion are changed to more than 11, so you do not have to introduce V4 package.

In the middle of the code there are two fragment subclasses, which have been seen contentfragment above, friendfragment in fact similar:

Package com.zhy.zhy_fragments; 
Import android.app.Fragment; 
Import Android.os.Bundle; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.view.ViewGroup; 
public class Friendfragment extends Fragment 
{ 
 @Override public 
 View Oncreateview (layoutinflater inflater , ViewGroup container, 
   Bundle savedinstancestate) 
 {return 
  inflater.inflate (r.layout.fragment_ Friend, container, false); 
 } 


Effect Chart:

Can see very good implementation of the effect, in fact, the effect of the previous blog has also appeared in the Blog: Android tab type main interface Big summary fragment+tabpageindicator+viewpager, interested to see. PS: For the simplicity of the code, do not add a button click changes or anything, mainly explain the function ~ ~ ~

5, the fragment family commonly used API

Fragment three commonly used classes:

Android.app.Fragment is primarily used to define Fragment

Android.app.FragmentManager is primarily used to manipulate fragment in activity

Android.app.FragmentTransaction guarantee the atomic nature of some column fragment operation, familiar with the word of business, must understand ~

A, the way to obtain Fragmentmanage:

Getfragmentmanager ()//V4, Getsupportfragmentmanager

b, the main operation is the Fragmenttransaction method

Fragmenttransaction transaction = Fm.bengintransatcion ();//Open a transaction

Transaction.add ()

Add a fragment to the activity

Transaction.remove ()

Removes a fragment from the activity, if the removed fragment is not added to the fallback stack (which is described later in the fallback stack), the fragment instance is destroyed.

Transaction.replace ()

Replace the current with another fragment, which is actually the remove () and add ()

Transaction.hide ()

Hides the current fragment, is only set to invisible, and does not destroy

Transaction.show ()

Displays the previously hidden fragment

Detach ()

Will remove view from the UI, unlike remove (), where the fragment state is still maintained by Fragmentmanager.

Attach ()

Rebuilds the view views, attaches to the UI, and displays.

Transatcion.commit ()//Commit a transaction

Note: Common fragment buddies may often encounter such an activity status inconsistency: The state loss such an error. This is mainly because: the commit method must be called before Activity.onsaveinstance ().

Above, basically is the operation of fragment all the way, in a transaction open to commit can be multiple add, remove, replace, and other operations.

It's worth noting: if you like using fragment, be sure to know which ones will destroy the view, which will destroy the instance, and which is just hidden, so you can use them better.

A, for example: I fill in the Fragmenta edittext some data, when switching to FRAGMENTB, if you want to see the data, then you are the hide and show, that is, you want to keep the user Action panel, you can use hide and show And, of course, don't push hard at that new instance, make a non null judgment.

B, another example: I do not want to retain user action, you can use remove (), and then add (), or use replace () this and remove,add is the same effect.

C, remove and detach have a slight difference, without considering the fallback stack, remove will destroy the entire fragment instance, and detach will only destroy its view structure, the instance will not be destroyed. So how do you choose to use them? If your current activity persists, you may prefer to use detach when you do not want to retain the user's actions.

This has been introduced to complete the fragment commonly used methods, I believe that after reading, we must clearly understand the reasons for fragment, and how to use fragment, and then according to the API explanation, can understand, once why feel fragment will appear some disorderly seven or eight slot problem, It is because the life cycle is not clear.

The following continues to give you an in-depth analysis of Android Fragment (next), interested friends continue to pay attention to this site, if this article where the wrong place to write welcome to my message, thank you!

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.