? "declaration"
Welcome reprint, but please keep the original source of the article →_→
Life One number: http://www.cnblogs.com/smyhvae/
Article Source: http://www.cnblogs.com/smyhvae/p/3978989.html
Contact information: [Email protected]
Body
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 primary research:
A fragment is a part or a behavior in the interface of an 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 a fragment is added to the 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 displayed on the tablet, Android introduced the Fragment (fragmentation) feature in version 3.0, which clearly shows the benefits of fragment through this image in the official documentation:
Note: The left side is flat and the right hand side is a handheld device.
Second, the life cycle of fragment:
Because fragment must be embedded in the acitivity, the life cycle of fragment is closely related to the activity in which it resides.
If the activity is paused, all of the fragment are paused, and if the 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.
Each time a fragment is created, the following three callback methods are added first:
- OnCreate (): The system calls this method when creating the fragment, where the related components should be initialized, and some things that need to be preserved even if they are 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 fragment into activity:
- Method One: Add fragment to the activity's layout file
- Mode two: Dynamically add fragment in the activity's code
The first approach 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 ).
Here's a look at the separate sections.
third, in the activity of the layout file Add Fragment :(not recommended)
The emulator parameters for the tablet are as follows:
Then create a new project file. Then proceed to the following steps:
(1) New file Fragment_hello.xml and Hellofragment.java:
The Fragment_hello.xml code is as follows: (i.e. fragment layout file)
<?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" > <edittext android:layout_width= "match_parent" android:layout_height= " Wrap_content " android:hint=" Please enter the content "/> <ratingbar android:id=" @+id/ratingbar1 " android: Layout_width= "Wrap_content" android:layout_height= "Wrap_content"/></linearlayout>
The Hellofragment.java code is as follows:
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.V Iew. View; 7 Import Android.view.ViewGroup; 8 9 public class Hellofragment extends Fragment {Ten @Override12 public void OnCreate (Bundle Savedinstancestate) { super.oncreate (savedinstancestate), }15 @Override17 public View Oncreateview (Layoutinflater inflater, ViewGroup container,18 Bundle savedinstancestate) { view view = Inflater.inflate (R.layout.fragment_hello, null); View Android.view.LayoutInflater.inflate (int resource, ViewGroup root) return view; }22 @Override24 public void OnPause () { super.onpause (); }27}
The focus is on lines 19th and 20, and the layout of the custom fragment is loaded in by the inflate () method.
In 19 lines of 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:
The code to modify Activity_main.xml is as follows:
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 "ten android:layout_width=" wrap_content " android:layout_height=" wrap_content "/ >12 </LinearLayout>
08 rows and 09 rows are key. Where the Android:name property fills in the full class name of the fragment you created yourself. Such as:
When the system creates a layout file for this activity, the system instantiates each fragment and calls their Oncreateview () method to get the layout of the corresponding fragment and inserts the return value into the fragment tag's location.
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 to the activity code:
Instance click the button in the left fragment to eject the fragment on the right. Create a new project file, and then proceed as follows:
(1) The the layout of the Activity_main is divided into two parts : 1/4 on the left and 3/4 on the right. The code to modify Activity_main.xml is as follows:
<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:la Yout_width= "0DP" android:layout_height= "match_parent" android:orientation= "vertical" android:layout_w eight= "1" android:background= "#00BFFF" > <button android:id= "@+id/button1" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:tex T= "Show"/> </LinearLayout> <linearlayout android:id= "@+id/right" Android:lay Out_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "3" android:background= "#0 0FFFF "android:orientation=" vertical " > </LinearLayout></LinearLayout>
In the above code, a linearlayout represents a fragment container, remember to add a container ID to each fragment. The layout of the above code works as follows:
Now that the two fragment have been allocated, then the fragment on the right is written.
(2) New file Fragment_right.xml and Rightfragment.java:
The Fragment_right.xml code is as follows: (Add a text and button)
<?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/textview1" android:layout_width= "Wrap_ Content " android:layout_height=" wrap_content " android:text=" News contents "/> <button android:id=" @+id/button2 " android:layout_width=" wrap_content " android:layout_height=" Wrap_content " android: text= "button"/></linearlayout>
The Rightfragment.java code is as follows:
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 () { super.onpause (); }}
Immediately after that, we modify the code in the above Oncreateview () method to implement a Click button that pops up the toast:
1 public view Oncreateview (Layoutinflater inflater, ViewGroup container, 2 Bundle savedinstancestate) {3 View VI ew = inflater.inflate (r.layout.fragment_right, NULL); 4 Button button = (button) View.findviewbyid (R.id.button2); 5 Button.setonclicklistener (new Onclicklistener () { 6 @Override 7 public void OnClick (View v) {8 Toast.maketext (Getactivity (), "I am Fragment", Toast.length_short). Show (); 9 }10 }); return view;12 }
The No. 04 line of code: there is a word view do not forget.
Line No. 08: The first parameter must be a getactivity to get the activity of the parent class
(3) Add fragment to the activity code:
Click the button on the left side of the mainactivity to eject the fragment on the right,
The code for the Listener section of Mainactivity.java is as follows:
1 button.setonclicklistener (new Onclicklistener () {2 3 @Override 4 6 // Step One: Add an instance of fragmenttransaction 7 fragmentmanager Fragmentmanager =getfragmentmanager (); 8 Fragmenttransaction transaction = Fragmentmanager.begintransaction (); 9 //Step Two: Use the Add () method plus fragment object Rightfragment one rightfragment rightfragment = new Rightfragment (); Transaction.add (R.id.right, rightfragment); transaction.commit (); }17 });
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. The container view resource ID has two functions:
- Tell Fragmentmanager,fragment where the view should appear in the Activity view
- is a unique identifier for fragment in the Fragmentmanager queue
After running, the effect is as follows:
When you click the left button, the right side of the screen appears. Click on the button on the right to eject the toast. The effect is as follows:
Of course, this code is not mature enough, because it also involves the life cycle is not processed. We'll explain in the next section.
Index
If you have doubts about this article, please refer to my series of articles on fragment: (constantly updated)
Android Series fragment (i)----fragment loaded into activity
Android Series fragment (ii)----fragment life cycle and return stack
Android Series fragment (iii)----communication between fragment and activity (with interface callbacks)
Android series fragment (iv) use of the----listfragment
Http://www.cnblogs.com/smyhvae/p/3978989.html
Android Series fragment (i)----fragment loaded into activity