Android Series fragment (i)----fragment loaded into activity

Source: Internet
Author: User

The interface display on Android is implemented through activity, and activity is too common. But activity also has its limitations, the same interface on the phone may look good, on the tablet is not necessarily, because the tablet screen is very large, the phone's interface on the tablet may be excessively stretched, the control spacing is too large, and so on. This is a better time to experience the effect of embedding "small activity" in activity, and then each "small activity" can have its own layout. Therefore, our protagonist fragment debut today.   First, Fragment:  fragment is a part or a behavior in the interface of activity. You can combine multiple fragment into one activity to create a faceted interface, and you can reuse a fragment in multiple activity. You can think of fragment as a modular activity that has its own life cycle, receives its own events, and can be added or deleted while the activity is running.  fragment cannot exist independently, it must be embedded in the activity, and the life cycle of fragment is directly affected by the activity in which it resides. For example, when activity is paused, all the fragment that it owns are paused, and when the activity is destroyed, all of its fragment are destroyed. However, when the activity is running (before Onresume (), OnPause (), you can manipulate each fragment individually, such as adding or removing them. When you perform the above transaction for fragment, you can add transactions to a stack that is managed by the activity and each of the stacks is a fragment transaction. With this stack, the fragment transaction can be executed in reverse, so that the return key (navigating backwards) can be supported at the fragment level.   When you add a fragment to an activity, it is placed in the ViewGroup control and needs to be defined fragment its own interface. You can declare fragment in the Layoutxml file, the element is:<fragment>;, you can create fragment in your code, and then add it to the ViewGroup control. However, fragment does not have to be placed in the activity interface, it can be hidden in the background for actvitiy work. Philosophy of   design:  to allow the interface to be better on the tabletShown, Android introduced the Fragment (fragment) feature in version 3.0, and this image in the official documentation can clearly see the benefits of fragment:    Note: Tablet on the left and handheld device on the right.     fragment life cycle:  because fragment must be embedded in acitivity, the life cycle of fragment is closely related to the activity in which it resides.   If activity is paused, all of the fragment are paused, and if activity is stopped state, all fragment in the activity cannot be activated, and if the activity is destroyed, Then all of its fragment will be destroyed.   However, when activity is active, you can independently control the state of the fragment, such as adding or removing fragment.   When this is done fragment transaction (conversion), you can put the fragment into the activity's back stack, so that the user can return the operation.   When using fragment, you need to inherit fragment or fragment subclasses (Dialogfragment, Listfragment, Preferencefragment, webviewfragment), So fragment's code looks similar to the activity.   Whenever a fragment is created, the following three callback methods are added first:  oncreate (): This method is called when the system creates the fragment, and the related components should be initialized. Something that needs to be preserved even when it is paused or stopped. Oncreateview (): When the fragment UI is first drawn, the system calls this method, which returns a view that can return NULL if fragment does not provide a UI. Note that if you inherit from Listfragment,oncreateview () The default implementation returns a ListView, so you don't have to implement it yourself. OnPause (): When a user leaves fragment, the first call to this method requires a change to be committed because the user is likely to no longer return. There are two ways to load the fragment into the activity:  one: Add fragment to the activity's layout file in the form two: in ACTIThe first way to dynamically add fragment in Vity code is simple but not flexible enough. Adding fragment to the activity's layout file is equivalent to binding fragment and its views to the activity's view, and cannot switch fragment views during the activity's life cycle.   The second approach is more complex, but it is also the only way to control fragment at run time (load, remove, replace).   The following will be introduced separately.     Add fragment to the activity's layout file: (not recommended)   the emulator parameters for the tablet are as follows:    and then create a new project file. Then continue with the following steps:  (1) New file Fragment_hello.xml and Hellofragment.java: fragment_hello.xml code are as follows: (that is, the fragment layout file)   Copy Code <?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:orientation=" vertical ">        <EditText         android:layout_width= "match_parent"         android:layout_height= "Wrap_content"         android:hint= "Please enter content"/>    <RatingBar        android:id= " @+id/ratingbar1 "  &NBSp     android:layout_width= "wrap_content"         android:layout_height= "wrap_content"/ ></LinearLayout> Copy Code   hellofragment.java code as follows:  copy code &NBSP;1 package com.example.m01_ Fragment01; 2  3 Import android.app.fragment; 4 Import android.os.bundle; 5 Import Android.view.layoutinflater; 6 Import android.view.view; 7 Import android.view.viewgroup; 8   9 public class Hellofragment extends Fragment {    11     @Override12     Publ IC void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate),    }15     16     @Override17     public View Oncreateview (Layoutinflater inflater, ViewGroup container,18             Bundle savedinstancestate) {      &NBS P View view = Inflater.inflate (R.layout.fragment_hello, NULL);  //View android.view.LayoutInflater.inflate (int resource, ViewGroup root)  20         return VI ew;21    }22     23     @Override24     public void OnPause () {+   &NB Sp     Super.onpause (), +    }27} The replication code focuses on lines 19th and 20 and loads the layout of the custom fragment through the inflate () method. In the  19 line code, in the second argument, if the layout has no root, then NULL is used.   NOTE: In the above code, since our program is facing Android 4.0 or later, when importing Fragment package, select the first:android.app.fragment    (2) Add fragment to the activity's layout:  modify Activity_main.xml code as follows:  copy code  1 <linearlayout xmlns:android= " Http://schemas.android.com/apk/res/android " 2     xmlns:tools=" Http://schemas.android.com/tools "  3     android:layout_width= "match_parent"  4     android:layout_height= "Match_parent"  5     tools:context= ". Mainactivity "> 6  7     <fragment 8         android:id=" @+id/ Fragment_hello " 9        android:name= "com.example.m01_fragment02. Hellofragment         android:layout_width= "wrap_content"         Android: layout_height= "Wrap_content"/>12 </LinearLayout> copy code 08 lines and 09 lines is key. Where the Android:name property fills in the full class name of the fragment you created yourself. such as:    when the system creates this activity's layout file, the system instantiates each fragment and calls their Oncreateview () method to get the layout of the corresponding fragment. and insert the return value where the fragment tag is located.   After running, the effect is as follows:    in fact, this approach is not recommended in development, so let's introduce another approach.     iv. Add fragment:  "instance" to the activity code click on the button in the left fragment to eject the fragment on the right. Create a new project file, and then proceed as follows:  (1) divides the layout of activity_main into two parts: 1/4 on the left and 3/4 on the right. The code to modify Activity_main.xml is as follows:  copy code <linearlayout 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"     tools:context= ". Mainactivity "    android:orientation=" Horizontal ">     <LinearLayout        android:id= "@+id/left"         Android: Layout_width= "0DP"         android:layout_height= "match_parent"         Android : orientation= "vertical"         android:layout_weight= "1"         Android: Background= "#00BFFF" >                <Button     & nbsp       android:id= ' @+id/button1 '             android:layout_width= ' WRAP_ Content "            android:layout_height=" wrap_content "                       android:text= "show"/>            < /linearlayout>     <LinearLayout         android:id= "@+id/right"               Android:Layout_width= "0DP"         android:layout_height= "match_parent"         Android: layout_weight= "3"         android:background= "#00FFFF"         Android:o rientation= "vertical" >     </LinearLayout> </LinearLayout> copy code above, A linearlayout represents a fragment container, remember to add a container ID to each fragment. The layout effect of the above code is as follows:    since two fragment of space are allocated, then the fragment on the right is written.   (2) New file Fragment_right.xml and Rightfragment.java: fragment_right.xml codes are as follows: (Add a text and button)   copy code <?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:orientation= "vertical" >     <TextView        android:id= "@+id/ TextView1 "        android:layout_width=" wrap_content "       android:layout_height= "Wrap_content"         android:text= "news content"/>     < button        android:id= "@+id/button2"         android:layout_width= "Wrap_ Content "        android:layout_height=" wrap_content "        android:text=" Button "/> </linearlayout> copy code Rightfragment.java code as follows:  copy code package com.example.m01_fragment03;  import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup; public class Rightfragment extends Fragment {    @ override    public void onCreate (Bundle savedinstancestate) {        Super.oncreate ( savedinstancestate);   }        @Override     public View Oncreateview ( Layoutinflater Inflater, ViewGroup container,            Bundle SavedinsTancestate) {        View view = Inflater.inflate (R.layout.fragment_right, NULL);        return view;   }        @Override     public void OnPause () {  & nbsp     Super.onpause ();   } Copy code immediately after, we modify the code in the above Oncreateview () method, implement the Click button, be able to pop up the toast:  copy code  1 Public View Oncreateview (Layoutinflater inflater, ViewGroup container, 2             Bu Ndle savedinstancestate) { 3         View view = Inflater.inflate (r.layout.fragment_right, NULL) ;  4         Button button = (button) View.findviewbyid (r.id.button2)  5         Button.setonclicklistener (new Onclicklistener () {            6     & nbsp       @Override  7             public void OnClick (View v) { 8 &nbsp ;       &nbsp       Toast.maketext (getactivity (), "I am Fragment", Toast.length_short). Show ();  9            }10        }),         return view;12     Copy code line No. 04: There is a word view don't forget.   NO. 08 Line of code: the first parameter must be getactivity, in order to get the parent class activity  (3) in the activity code to add fragment:  click on the left button in Mainactivity, The code for the listener portion of the fragment, mainactivity.java that pops up on the right is as follows:  copy code  1         Button.setonclicklistener (New Onclicklistener () { 2              3   & nbsp         @Override  4             public void OnClick (View v) {  5  6                //Step One: Add an instance of Fragmenttransaction  7   &NB Sp             Fragmentmanager Fragmentmanager =getfragmentmanager ()  8     &NB Sp         &NBsp Fragmenttransaction transaction = fragmentmanager.begintransaction ()  9 10                //Step two: Use the Add () method to add fragment objects rightfragment 11             &N Bsp   Rightfragment rightfragment = new Rightfragment (),                 TRANSA Ction.add (R.id.right, rightfragment), 13 14                //Step three: Call Commit () This method makes the change of Fragmenttransaction instance effective                 transaction.commit ();                16            }17     &NBS P  ); Copy the code to remember the three steps above. The   12th line of code is the core of the entire program. The first parameter in the Add () method is the container view resource ID, not layout. Container View resource ID has two functions:  tells Fragmentmanager,fragment where the view should appear in the Activity view is the unique identifier fragment in the Fragmentmanager queue

Android Series fragment (i)----fragment loaded into activity

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.