Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/8881711
We all know that the interface display on Android is implemented through activity, activity is too often used, I believe we are already very familiar with, here will not repeat.
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.
Preliminary study on fragment
To allow the interface to be better displayed on the tablet, Android introduced the Fragment (fragmentation) feature in version 3.0, which is very similar to activity and can include layouts like activity. Fragment is usually nested in the activity, now imagine this scenario: there are two Fragment,fragment 1 contains a ListView, each line shows the title of a book. Fragment 2 contains TextView and ImageView to show the details and pictures of the book.
If the program is now running in portrait mode on a tablet or phone, Fragment 1 may be embedded in one activity, while Fragment 2 may be embedded in another activity, as shown in:
And if the program is now running on a flat screen mode, two fragment can be embedded in the same activity as shown:
As you can see, using fragment allows us to make the most of our tablet's screen space, and here we explore how to use fragment.
The first thing to note is that fragment was introduced in version 3.0, and if you are using a system before 3.0, you need to import the ANDROID-SUPPORT-V4 jar package before you can use the fragment feature.
Create a new project called Fragments, and then create a new layout file named Fragment1.xml under the Layout folder:
[HTML] view plain copy
- <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
- Android:layout_width= "Match_parent"
- android:layout_height= "Match_parent"
- android:background= "#00ff00" >
- <textview
- Android:layout_width= "Wrap_content"
- android:layout_height= "Wrap_content"
- Android:text= "This is fragment 1"
- Android:textcolor= "#000000"
- Android:textsize= "25SP"/>
- </LinearLayout>
As you can see, this layout file is very simple and there is only one linearlayout, which adds a textview. We create a new fragment2.xml:
[HTML] view plain copy
- <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
- Android:layout_width= "Match_parent"
- android:layout_height= "Match_parent"
- android:background= "#ffff00" >
- <textview
- Android:layout_width= "Wrap_content"
- android:layout_height= "Wrap_content"
- Android:text= "This is Fragment 2"
- Android:textcolor= "#000000"
- Android:textsize= "25SP"/>
- </LinearLayout>
Then create a new class Fragment1, this class is inherited from the fragment:
[Java] view plain copy
- public class Fragment1 extends Fragment {
- @Override
- Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
- Return Inflater.inflate (R.layout.fragment1, container, false);
- }
- }
As we can see, this class is also very simple, mostly loading the fragment1.xml layout file we just wrote and returning it. In the same way, we'll write the Fragment2 again:
[Java] view plain copy
- public class Fragment2 extends Fragment {
- @Override
- Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
- Return Inflater.inflate (R.layout.fragment2, container, false);
- }
- }
Then open or create a new activity_main.xml as the main activity layout file, add two fragment references, use the Android:name prefix to refer to the specific fragment:
[HTML] view plain copy
- <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
- Android:layout_width= "Match_parent"
- android:layout_height= "Match_parent"
- Android:baselinealigned= "false" >
- <fragment
- Android:id= "@+id/fragment1"
- Android:name= "Com.example.fragmentdemo.Fragment1"
- Android:layout_width= "0dip"
- android:layout_height= "Match_parent"
- android:layout_weight= "1"/>
- <fragment
- Android:id= "@+id/fragment2"
- Android:name= "Com.example.fragmentdemo.Fragment2"
- Android:layout_width= "0dip"
- android:layout_height= "Match_parent"
- android:layout_weight= "1"/>
- </LinearLayout>
Finally open or new mainactivity as the main activity of the program, the code inside is very simple, are automatically generated:
[Java] view plain copy
- public class Mainactivity extends Activity {
- @Override
- protected void OnCreate (Bundle savedinstancestate) {
- Super.oncreate (savedinstancestate);
- Setcontentview (R.layout.activity_main);
- }
- }
Now let's run the program once, and we'll see that an activity contains two fragment, two fragment split the entire screen, as follows:
Add fragment Dynamically
You've learned how to use fragment in XML, but this is just the simplest feature of fragment. The real strength of fragment is that it can be dynamically added to the activity, so that's what you have to master. When you learn to add fragment to the activity while the program is running, the interface of the program can be customized more varied. Now we'll see how to add fragment dynamically.
Or on the basis of the previous section of the code to modify, open activity_ Main.xml, the reference to fragment is deleted, only the outermost linearlayout is preserved, and an ID is added to it, because we want to add fragment dynamically, without adding it in the XML, the following code is removed:
[HTML] view plain copy
- <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
- Android:id= "@+id/main_layout"
- Android:layout_width= "Match_parent"
- android:layout_height= "Match_parent"
- Android:baselinealigned= "false" >
- </LinearLayout>
Then open mainactivity and modify the code as follows:
[Java] view plain copy
- public class Mainactivity extends Activity {
- @Override
- protected void OnCreate (Bundle savedinstancestate) {
- Super.oncreate (savedinstancestate);
- Setcontentview (R.layout.activity_main);
- Display display = Getwindowmanager (). Getdefaultdisplay ();
- if (Display.getwidth () > Display.getheight ()) {
- Fragment1 fragment1 = new Fragment1 ();
- Getfragmentmanager (). BeginTransaction (). replace (R.id.main_layout, fragment1). commit ();
- } else {
- Fragment2 Fragment2 = new Fragment2 ();
- Getfragmentmanager (). BeginTransaction (). replace (R.id.main_layout, Fragment2). commit ();
- }
- }
- }
First, we want to get the width and height of the screen, and then judge if the screen width is greater than the height of the add fragment1, if the height is greater than the width of the add Fragment2. Dynamically adding fragment is divided into 4 main steps:
1. Access to Fragmentmanager, which can be obtained directly through Getfragmentmanager in the activity.
2. Open a transaction by calling the BeginTransaction method.
3. Adding fragment to the container, typically implemented with the Replace method, requires passing in the ID of the container and an instance of fragment.
4. Commit the transaction and invoke the Commit method commit.
Now run the program with the effect as shown:
If you are running with the emulator, press CTRL + F11 to switch to portrait mode. The effect is as follows:
The life cycle of fragment
Like activity, fragment has its own life cycle, it is important to understand the life cycle of fragment, and we look at how the life cycle of fragment is based on code:
[Java] view plain copy
- public class Fragment1 extends Fragment {
- public static final String TAG = "Fragment1";
- @Override
- Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
- LOG.D (TAG, "Oncreateview");
- Return Inflater.inflate (R.layout.fragment1, container, false);
- }
- @Override
- public void Onattach (activity activity) {
- Super.onattach (activity);
- LOG.D (TAG, "Onattach");
- }
- @Override
- public void OnCreate (Bundle savedinstancestate) {
- Super.oncreate (savedinstancestate);
- LOG.D (TAG, "onCreate");
- }
- @Override
- public void onactivitycreated (Bundle savedinstancestate) {
- Super.onactivitycreated (savedinstancestate);
- LOG.D (TAG, "onactivitycreated");
- }
- @Override
- public void OnStart () {
- Super.onstart ();
- LOG.D (TAG, "OnStart");
- }
- @Override
- public void Onresume () {
- Super.onresume ();
- LOG.D (TAG, "Onresume");
- }
- @Override
- public void OnPause () {
- Super.onpause ();
- LOG.D (TAG, "onPause");
- }
- @Override
- public void OnStop () {
- Super.onstop ();
- LOG.D (TAG, "onStop");
- }
- @Override
- public void Ondestroyview () {
- Super.ondestroyview ();
- LOG.D (TAG, "Ondestroyview");
- }
- @Override
- public void OnDestroy () {
- Super.ondestroy ();
- LOG.D (TAG, "OnDestroy");
- }
- @Override
- public void Ondetach () {
- Super.ondetach ();
- LOG.D (TAG, "Ondetach");
- }
- }
As you can see, the above code prints the log in every life cycle method, and then we run the program and see the print log as follows:
At this point, click the Home button, print the log as follows:
If you re-enter the program again, print the log as follows:
Then click the Back button to exit the program, print the log as follows:
Seeing here, I believe most of my friends are very clear, because it is too similar to the life cycle of the activity. There are only a few new methods that are not available in the activity, so here are some highlights:
- Onattach method: Called when fragment is associated with an activity.
- Oncreateview method: Called when the layout is loaded for fragment.
- Onactivitycreated method: Called when the OnCreate method in the activity finishes executing.
- Ondestroyview method: Called when the layout in the fragment is removed.
- Ondetach method: Called when fragment and activity are disassociate.
Communication between the fragment
Typically, the activity will contain multiple fragment, so how to communicate between multiple fragment is a very important issue. Let's look at an example of how to access another fragment view in one fragment.
Or on the basis of the first section of the code to modify, first open fragment2.xml, in this layout to add a button:
[HTML] view plain copy
- <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
- Android:layout_width= "Match_parent"
- android:layout_height= "Match_parent"
- android:orientation= "Vertical"
- android:background= "#ffff00" >
- <textview
- Android:layout_width= "Wrap_content"
- android:layout_height= "Wrap_content"
- Android:text= "This is Fragment 2"
- Android:textcolor= "#000000"
- Android:textsize= "25SP"/>
- <button
- Android:id= "@+id/button"
- Android:layout_width= "Wrap_content"
- android:layout_height= "Wrap_content"
- android:text= "Get fragment1 text"
- />
- </LinearLayout>
Then open Fragment1.xml and add an ID for TextView:
[HTML] view plain copy
- <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
- Android:layout_width= "Match_parent"
- android:layout_height= "Match_parent"
- android:background= "#00ff00" >
- <textview
- Android:id= "@+id/fragment1_text"
- Android:layout_width= "Wrap_content"
- android:layout_height= "Wrap_content"
- Android:text= "This is fragment 1"
- Android:textcolor= "#000000"
- Android:textsize= "25SP"/>
- </LinearLayout>
Then open Fragment2.java, add the Onactivitycreated method, and handle the button's Click event:
[Java] view plain copy
- public class Fragment2 extends Fragment {
- @Override
- Public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
- Return Inflater.inflate (R.layout.fragment2, container, false);
- }
- @Override
- public void onactivitycreated (Bundle savedinstancestate) {
- Super.onactivitycreated (savedinstancestate);
- Button button = (button) getactivity (). Findviewbyid (R.id.button);
- Button.setonclicklistener (New Onclicklistener () {
- @Override
- public void OnClick (View v) {
- TextView TextView = (TextView) getactivity (). Findviewbyid (R.id.fragment1_text);
- Toast.maketext (Getactivity (), Textview.gettext (), Toast.length_long). Show ();
- }
- });
- }
- }
Now run the program and click on the button on the Fragment2, as shown in the results:
We can see that the view in Fragment1 was successfully obtained in Fragment2 and the toast was popped. How is this going to be achieved? Mainly through the Getactivity this method is implemented. The Getactivity method allows fragment to obtain the associated activity and then invoke the Findviewbyid method of the activity to obtain a view of the other fragment associated with the activity.
Well, that's all you need to know about fragment. If you want to experience the actual combat of fragment, please continue to read the Android phone tablet, using fragment to achieve compatible mobile phone and tablet programs and Android fragment application combat, use fragments to say goodbye to Activitygroup.
First time to get blog update reminders, as well as more technical information sharing, welcome to follow my public number, sweep the QR code below or search number Guolin_blog, you can pay attention to.
Second, the use of fragment