Click here to download the full source ~(code for this article)
1, create a project named "Fragments", under the Res/layout folder, the new Fragment1.xml, Fragment2.xml, respectively, under the current package name, the new Fragment1.java, Fragment2.java:
Fragment1.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" fill_parent " android:layout_height=" fill_parent " android:background = "#00FF00" android:orientation= "vertical" > <textview android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "This is fragment #1" android:textcolor= "#000000" Android:textsize= "25SP"/></linearlayout>
Fragment2.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" fill_parent " android:layout_height=" fill_parent " android:background = "#FFFE00" android:orientation= "vertical" > <textview android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "This is fragment #2" android:textcolor= "#000000" Android:textsize= "25SP"/></linearlayout>
Fragment1.java:
Package Net.zenail.fragments;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class Fragment1 extends Fragment {//Inherit Fragment base class//Draw fragment UI: Use a Layoutinflauter object to increase the UI in the specified XML file. The container parameter refers to the parent ViewGroup, which prepares the activity for embedding fragmentation. The Savedinstancestate parameter allows the fragment to be restored to the previous saved state. @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {//TODO Auto-generated method Stubreturn inflater.inflate (R.layout.fragment1, container, false);}}
Fragment2.java:
Package Net.zenail.fragments;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class Fragment2 extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {/ /TODO auto-generated method Stubreturn inflater.inflate (R.layout.fragment2, container, false);}}
2. Add two fragments to the Main.xml file:
<fragment android:id= "@+id/fragment1" android:name= "Net.zenail.fragments.Fragment1" android: Layout_width= "0px" android:layout_height= "match_parent" android:layout_weight= "1" tools:layout= "@ Layout/fragment1 "/> <fragment android:id=" @+id/fragment2 " android:name=" Net.zenail.fragments.Fragment2 " android:layout_width=" 0px " android:layout_height=" Match_parent " android:layout_weight= "1" tools:layout= "@layout/fragment2"/>
3, operation, the effect is as follows: