Android Fragment Use

Source: Internet
Author: User

The preface has been learning Java and Android for nearly a year, and the result should be to independently complete an Android client "play the game" and ensure its stability in the mainline version. During the encounter a lot of pits, but also follow my brother learned a lot of Android knowledge. But people always want to embrace change, can not let themselves too comfortable, although there is not, but I have proved their ability to learn, the next step is to start to do ROM porting. Here's a summary of the most used fragment in the previous project.
Fragment introduction fragment can be understood as a behavior or part of the user interface in activity, and it must be nested within the activity. But a fragment has its own independent XML layout file and is well encapsulated, so fragment can easily be replaced with activity in special cases.
Creating a fragment creates a fragment similar to creating an activity, which requires implementing an XML layout file and Java Class. The XML layout file and other layout files are the same, such as the layout file (fragment_layout.xml) as shown below:
<?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/textview" android:layout_width= "Wrap_        Content "        android:layout_height=" wrap_content "        android:text=" @string/testview "/>    <button        Android:id= "@+id/button"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android:text= "@string/button"/></linearlayout>
In Java code, the following life-cycle methods can typically be implemented fragment as needed:
1. Onattach (): When fragment is attached to the activity, the activity handle can be obtained in this method to achieve communication between the fragment and the activity. 2. OnCreate (): initializes the fragment. 3. Oncreateview (): The system calls this method the first time the user interface is drawn for fragment. 4. onactivitycreated (): Called after the execution of the host activity OnCreate function is completed, you can fragment your own widget instantiation and business logic processing in this method. 5. Ondestoryview (): Called when fragment begins to be destroyed. 6. OnStart (): Called when fragment is visible. There are many other callback functions to manipulate the stages of the fragment life cycle, and you can learn from Google yourself.
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 as follows:

Join fragment in activity first, you need to make sure that acitivity supports fragment, so activity usually needs to inherit from Fragmentactivity. There are two ways to add fragment in activity: static and dynamic. The static method joins fragment directly in the activity's XML layout file, as follows:
<?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 "and        Roid:baselinealigned= "false" android:orientation= "Horizontal" > <fragment android:id= "@+id/first"        Android: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.Sec Ondfragment "android:layout_width=" 0DP "android:layout_height=" Match_parent "android:layout_weight=" 1 "/></LINEARLAYOUT> 
The Android:name property in <fragment> specifies the fragment class that is instantiated in the layout when the system creates an activity layout, it instantiates every fragment specified in the layout file. and call the Oncreateview () function for them to get a layout for each fragment. The system inserts the fragment return view directly at the <fragment> element location 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 an ID for fragment:
    • Provide a unique identity with the Android:id property
    • Provide a unique string with the Android:tag property
    • If neither of these properties is available, the system uses the ID of its container view
Dynamic methods use Fragmenttranscation. You can use the Fragmenttranscation API to manipulate the activity's fragment (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 viewgroup that fragment is placed on, which is specified by the resource ID (resource ID), and the second parameter is the fragment to be added. Once a change has been made through fragmenttranscation, the change should be applied using commit ().
Fragments communication fragments should not communicate directly between them, the interaction between them should be carried out through the host activity. There are three ways to interact with fragment and acitivity: 1. Activity creates a fragment with parameters. 2. The fragment object handle is maintained in the activity, and the public method of the fragment can be called directly through the handle. 3. Fragment can get the defined listener handle in the Onattach function. Create fragment with parameters in some specific cases, fragment may require specific parameters to initialize. Since fragment must have only one parameterless constructor, consider using the static Newinstance method to create 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) {Testfragment fragment = new Testfragment (); Bundle args = new Bundle (), Args.putint ("num", num), args.putstring ("title", title); fragment.setarguments (args); return Fragment;} @Overridepublic 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 ();
Call fragment method because activity can get the handle of an embedded fragment, so you can call the method directly from the fragment handle.
public class Testfragment extends Fragment {public void dosomething (String param) {//does something in Fragment}}
In activity, the method can be called directly from 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 This method is required if Fragment needs to share events with the activity. An interface is defined in fragment and implemented by the activity. In the Onattach () method, the activity that implements the interface 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 T  He interface type//listener is the activity itself private onitemselectedlistener listener; Define the events that the fragment would use a communicate public interface Onitemselectedlistener {public void O  nrssitemselected (String link); }//Store the Listener (activity) that'll has events fired once the fragment is attached @Override public void Onat      Tach (activity activity) {Super.onattach (activity);      if (activity instanceof onitemselectedlistener) {listener = (onitemselectedlistener) activity; } else {throw new ClassCastException (activity.tostring () + "must implement Mylistfragment.onitemselect      Edlistener ");     }}//Now we can fire the event if the user selects something in the Fragment public void Onsomeclick (View v) {  listener.onrssitemselected ("some link"); }}
Implement this interface in 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 activity when the fragment event fires  @Override public  void Onrs sitemselected (String link) {      if (fragment! = null && fragment.isinlayout ()) {          fragment.settext (link) ;      }  }}

Android Fragment Use

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.