Explain the use of fragment in Android development _java

Source: Internet
Author: User

Objective
after nearly a year of learning Java and Android, the result should be a standalone Android client that ensures its stability in the mainline version. During the encounter a lot of pits, but also with brother learned a lot of Android knowledge. But people always want to embrace change, can not let oneself too comfortable, although have not shed, but I have proven their ability to learn, the next step is to start doing ROM porting. Here's a summary of the most used fragment in previous projects.

Fragment Introduction
fragment can be understood as a behavior or part of the user interface in an activity, and it must be nested within the activities. However, a fragment has its own independent XML layout file and has good encapsulation, so fragment can easily be replaced with activity in special cases.

Create fragment
creating a fragment is similar to creating an activity, which requires implementing an XML layout file and Java Class.
The XML layout file is the same as other layout files, such as the layout file (fragment_layout.xml) shown below:

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Chemas.android.com/apk/res/android "android:layout_width=" match_parent "android:layout_height=" Match_parent "Andr" 
   oid:orientation= "vertical" > <textview android:id= "@+id/textview" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "@string/testview"/> <button android:id= "@+id/b Utton "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:text=" "@string/button" /> </LinearLayout> 

In Java code, it is generally possible to implement the following lifecycle methods as needed: Fragment
1. Onattach (): When fragment is called when attached to an activity, it is possible to obtain an activity handle in the method to achieve communication between the fragment and the activity.
2. OnCreate (): Initialization of fragment.
3. Oncreateview (): This method is called the first time the user interface is drawn for fragment.
4. onactivitycreated (): Invoked after the execution of the host activity OnCreate function, you can fragment your own widget instantiation and business logic in this method.
5. Ondestoryview (): Called when fragment is started to be destroyed.
6. OnStart (): Called when fragment is visible.
There are many other callback functions that manipulate the various stages of the fragment lifecycle, and you can learn from Google.

Fragment life cycle
each fragment has its own set of lifecycle callback methods and handles its own user input events. The corresponding life cycle is shown in the following illustration:

Adding fragment to the activity
first, you need to ensure that acitivity supports fragment, so the activity usually needs to inherit from Fragmentactivity. There are usually two ways to add fragment to an activity: static and dynamic.
static method
Add fragment directly to the XML layout file for the activity, as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Chemas.android.com/apk/res/android "android:layout_width=" match_parent "android:layout_height=" Match_parent "Andr" Oid:baselinealigned= "false" android:orientation= "Horizontal" > <fragment android:id= "@+id/first" an Droid:name= "Com.example.FristFragment" android:layout_width= "0DP" android:layout_height= "Match_parent" Android 
   : layout_weight= "1"/> <fragment android:id= "@+id/second" android:name= "Com.example.SecondFragment" Android:layout_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "1"/> </LinearL Ayout> 

The Android:name property in <fragment> specifies the fragment class instantiated in the layout
When the system creates an activity layout, it instantiates each of the fragment specified in the layout file and calls the Oncreateview () function for them to get the layout of each fragment. The system inserts the fragment returned view directly at the <fragment> element position
Note: Each fragment requires a unique identity, and if the activity is restarted, the system can be used to recover fragment (and to capture fragment transactions, such as removal). There are three ways to provide IDs for fragment:

    • Provides a unique identity with the Android:id property
    • Provides a unique string with the Android:tag property
    • If none of the above two properties are available, the system uses the ID of its container view

Dynamic method
use Fragmenttranscation. You can use the Fragmenttranscation API to manipulate the fragment of an activity (for example, add, remove, or replace fragment). The reference code is as follows:

 Fragmentmanager Fragmentmanager = Getfragmentmanager () 
 fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction (); 
 Examplefragment fragment = new Examplefragment (); 
 Fragmenttransaction.add (R.id.fragment_container, fragment); 
 Fragmenttransaction.commit (); 

The first parameter of the incoming add () function is the fragment placed ViewGroup, which is specified by the resource ID (resource ID) and the second parameter is the fragment to add. Once a change has been made through fragmenttranscation, a commit () should be used as a change in effect.

Fragments Communication
there should be no direct communication between fragments, and the interaction between them should be done through host activity. There are three ways to interact with fragment and acitivity:
1. Activity creates a fragment with parameters.
2. The fragment object handle, which is maintained in the activity, invokes the fragment public method directly from the handle.
3. Fragment can get the defined listener handle in the Onattach function.
to create a fragment with parameters
in some specific cases, fragment may require specific parameters for initialization. Because fragment must have only one parameterless constructor, you can consider using a static Newinstance method to create a fragment with parameters. The sample code is as follows:

 Import Android.os.Bundle; 
 Import android.support.v4.app.Fragment; 
  
 public class Testfragment extends Fragment {public 
  static testfragment newinstance (int num, String title) { 
   TESTF Ragment fragment = new Testfragment (); 
   Bundle args = new Bundle (); 
   Args.putint ("num", num); 
   Args.putstring ("title", title); 
   Fragment.setarguments (args); 
   return fragment; 
  } 
  
  @Override public 
  void OnCreate (Bundle savedinstancestate) { 
   super.oncreate (savedinstancestate); 
  
   int num = getarguments (). GETINT ("num", 0); 
   String title = Getarguments (). getString ("title", ""); 
  } 
  
 } 

You can simply load a fragment with parameters in the activity:

 Fragmenttransaction ft = Getsupportfragmentmanager (). BeginTransaction (); 
 Testfragment fragment = Testfragment.newinstance (5, "fragment title"); 
 Ft.replace (R.id.placeholder, fragment); 
 Ft.commit (); 

Method of calling Fragment
because the activity can get the handle of the embedded fragment, the method can be called directly through the fragment handle.

 public class Testfragment extends Fragment {public 
  void dosomething (String param) { 
   //does something in fragment
   } 
 } 

In an activity, the method can be invoked directly through the fragment object handle:

 public class Mainactivity extends Fragmentactivity { 
  @Override public 
  void OnCreate (Bundle savedinstancestate) { 
   super.oncreate (savedinstancestate); 
   Testfragment testfragment = new Testfragment (); 
   Testfragment.dosomething ("some param"); 
  } 
  

Fragment Listener
if fragment needs to share events with the activity, you need to take advantage of this approach. An interface is defined in the fragment and is implemented by the activity. The activity that implements this interface in the Onattach () method is obtained.
Define the interface code in fragment as follows:

Import android.support.v4.app.Fragment;  public class Mylistfragment extends Fragment {//Define the listener of the interface type//listener is 
  
  The activity itself private onitemselectedlistener listener;  Define the events that the fragment would use to communicate public interface Onitemselectedlistener {public void 
  onrssitemselected (String link); }//Store the Listener (activity) that'll have events fired once the fragment is attached @Override public 
   void Onattach (activity activity) {Super.onattach (activity); 
   if (activity instanceof onitemselectedlistener) {listener = (onitemselectedlistener) activity; else {throw new ClassCastException (activity.tostring () + must implement Mylistfragment.onitemselectedlistene 
   R "); }//Now we can fire the event as the user selects something in the Fragment public void Onsomeclick (View 
  V) {listener.onrssitemselected ("some link"); 
} } 
 

Implement this interface in the activity:

Import android.support.v4.app.FragmentActivity; 
  
 public class Rssfeedactivity extends Fragmentactivity implements 
  Mylistfragment.onitemselectedlistener { 
  Detailfragment fragment; 
  
  @Override 
  protected void onCreate (Bundle savedinstancestate) { 
   super.oncreate (savedinstancestate); 
   Setcontentview (r.layout.activity_rssfeed); 
   Fragment = (detailfragment) Getsupportfragmentmanager () 
    . Findfragmentbyid (r.id.detailfragment); 
  
  Now we can define the "action to take" in the Fragment event fires 
  @Override public 
  void Onrs sitemselected (String link) { 
   if (fragment!= null && fragment.isinlayout ()) { 
    fragment.settext (link) ; 
   } 
  } 
 } 

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.