Real full parsing of fragment in Android (top) _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 ~ ~ ~

This article seeks to explain how fragment produces, what is the fragment,fragment lifecycle, how static and dynamic use of fragment,fragment fallback stack, fragment affairs; and fragment some special uses, 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 screens
Screen of mobile phone, oversized screen or even TV. 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://schemasandroidcom/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 comzhyzhy_fragments; 
Import androidappfragment; 
Import Androidosbundle; 
Import Androidviewlayoutinflater; 
Import Androidviewview; 
Import Androidviewviewonclicklistener; 
Import Androidviewviewgroup; 
Import Androidwidgetimagebutton; 
 
Import Androidwidgettoast; 
 
  public class Titlefragment extends Fragment {private ImageButton mleftmenu;  
    @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { 
    View view = Inflaterinflate (Rlayoutfragment_title, container, false); 
    Mleftmenu = (ImageButton) Viewfindviewbyid (RIDID_TITLE_LEFT_BTN); 
        Mleftmenusetonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { Toastmaketext (Getactivity (), "I am a ImageButton in titlefragment!", Toastlength_short) s 
      how (); 
    } 
    }); 
  return view; } 
} 

Similarly, there are Contentfragment's layout files:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"Http://schemasandroidcom/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"/> 
 
</LinearLayout> 
Package com.zhy.zhy_fragments; 
 
Import androidappfragment; 
Import Androidosbundle; 
Import Androidviewlayoutinflater; 
Import Androidviewview; 
Import Androidviewviewgroup; 
 
public class Contentfragment extends Fragment 
{ 
 
  @Override public 
  View Oncreateview (layoutinflater Inflater, ViewGroup container, 
      Bundle savedinstancestate) 
  {return 
    inflaterinflate (rlayoutfragment_ Content, container, false); 
  } 
 
 

Mainactivity

Package com.zhy.zhy_fragments; 
 
Import androidappactivity; 
Import Androidosbundle; 
Import Androidviewwindow; 
 
public class Mainactivity extends activity 
{ 
 
  @Override 
  protected void OnCreate (Bundle Savedinstancestate) 
  { 
    superoncreate (savedinstancestate); 
    Requestwindowfeature (windowfeature_no_title); 
    Setcontentview (Rlayoutactivity_main); 
  } 
 
 

The layout file for the activity:

<relativelayout xmlns:android= "http://schemasandroidcom/apk/res/android" 
  xmlns:tools= "http:// Schemasandroidcom/tools " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent "> 
 
  <fragment 
    android:id= "@+id/id_fragment_title" 
    android:name= "Comzhyzhy_fragmentstitlefragment" 
    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= "Comzhyzhy_ Fragmentscontentfragment " 
    android:layout_width=" fill_parent " 
    android:layout_height=" Fill_parent " > 
 

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:// Schemasandroidcom/tools " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent "> 
 
  <fragment 
    android:id= "@+id/id_fragment_title" 
    android:name= "Comzhyzhy_fragmentstitlefragment" 
    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 primary activity

Package com.zhy.zhy_fragments; 
Import androidappactivity; 
Import Androidappfragmentmanager; 
Import androidappfragmenttransaction; 
Import Androidosbundle; 
Import Androidviewview; 
Import Androidviewviewonclicklistener; 
Import Androidviewwindow; 
 
Import Androidwidgetlinearlayout; 
  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) {superoncreate (savedinstancestate); 
    Requestwindowfeature (Windowfeature_no_title); 
 
    Setcontentview (Rlayoutactivity_main); 
    Initializes the control and declares the event Mtabweixin = (linearlayout) Findviewbyid (ridtab_bottom_weixin); 
    Mtabfriend = (linearlayout) Findviewbyid (ridtab_bottom_friend); 
    Mtabweixinsetonclicklistener (this); 
 
    Mtabfriendsetonclicklistener (this); Set the default fragment SetdefaultfraGment (); 
    private void Setdefaultfragment () {Fragmentmanager fm = Getfragmentmanager (); 
    Fragmenttransaction transaction = Fmbegintransaction (); 
    Mweixin = new Contentfragment (); 
    Transactionreplace (Ridid_content, mweixin); 
  Transactioncommit (); 
    @Override public void OnClick (View v) {Fragmentmanager fm = Getfragmentmanager (); 
 
    Open fragment transaction Fragmenttransaction transaction = Fmbegintransaction (); Switch (Vgetid ()) {case Ridtab_bottom_weixin:if (mweixin = = null) {mweixin = new Conte 
      Ntfragment (); 
      ////Use the current fragment layout instead of the Id_content control Transactionreplace (Ridid_content, mweixin); 
    Break 
      Case Ridtab_bottom_friend:if (mfriend = = null) {mfriend = new friendfragment (); 
      } transactionreplace (Ridid_content, mfriend); 
    Break 
    }//Transactionaddtobackstack (); 
  Transaction submitted to Transactioncommit (); } 
 
} 
 

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 androidappfragment; 
Import Androidosbundle; 
Import Androidviewlayoutinflater; 
Import Androidviewview; 
Import Androidviewviewgroup; 
 
public class Friendfragment extends Fragment 
{ 
 
  @Override public 
  View Oncreateview (layoutinflater inflater , ViewGroup container, 
      Bundle savedinstancestate) 
  {return 
    inflaterinflate (Rlayoutfragment_friend, container, False); 
  } 
 
 

Effect Chart:

can see very good realization of the effect, in fact, the effect of the previous blog has also appeared, Fragment+tabpageindicator+viewpager, interested can 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

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.

For space reasons, the rest of the content is left to the next article. In the next article, we will introduce:

1, how to manage fragment back stack

2. How fragment interacts with the activity

3. Best practices for interaction between fragment and activity

4, no view of the use of fragment

5, use fragment to create a dialog box

6, how to integrate with Actionbar,menuitem ~ ~

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.