Android Fragment Simple Example

Source: Internet
Author: User

The interface display on Android is implemented through activity. The activity is too often used. I believe we are already familiar with this, and we will not repeat it here. However, the activity also has its limitations, the same interface on the phone may look good, on the tablet is not necessarily, because the flat screen is very large. The phone's interface on the tablet may be excessively elongated, the control spacing is too large and so on. A better experience at this time is to embed "small activity" in the activity. Then each "little activity" can have its own layout. This is fragment fragmentation technology.

First, Fragment simple introduction

Android was introduced at Android 3.0 (API level 11) and started to introduce fragment. The ability to think of fragment as a module in activity, which has its own layout, has its own life cycle, handles its own input individually, and can load or remove the fragment module when the activity executes.

The ability to design fragment as a module that can be reused in multiple activity.

When developing applications for tablets and phones at the same time. The ability to use fragment to enable flexible layouts and improve the user experience.

Second, fragment life cycle

Because the fragment must be embedded in the acitivity for use. So the life cycle of fragment is closely related to the activity in which it resides.


Assume that activity is a paused state. All of the fragment are paused, assuming the activity is a stopped state. All the fragment in this activity cannot be started. Assuming the activity is destroyed, all of its fragment will be destroyed. However, when the activity is in the active state. The ability to independently control the state of the fragment, for example by adding or removing fragment.


When this is done fragment transaction (conversion), the fragment can be put into the activity's back stack. This allows the user to return operations.
  
Activity and fragment life cycle contrast chart
  

Three, two simple examples
    1. Simple fragment exercises, activity and fragment communication

      Layout file Activity_main.xml
<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 " android:orientation  =" vertical " tools:context  =;     <framelayoutandroid:layout_weight="1"android:id="@+id/content"  android:layout_width="Wrap_content"android:layout_height="0DP" >                                     </framelayout>    <android.support.v4.app.FragmentTabHostandroid:id="@+id/tab"android: Layout_width="Fill_parent"android:layout_height="wrap_content" />                        </linearlayout>

Java files

 PackageCom.example.fragmenttabhost;ImportAndroid.os.Bundle;ImportAndroid.support.v4.app.ListFragment;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.Toast; Public  class myfragment extends listfragment{String show1[] = {"1.1","1.2","1.3","1.4"}; String show2[] = {"2.1","2.2","2.3","2.4"};@Override     Public void onactivitycreated(Bundle savedinstancestate) {Super. onactivitycreated (Savedinstancestate); String show[] =NULL; Bundle bundle = Getarguments ();if(Bundle = =NULL) show = Show1;Else{show = Show2; Toast.maketext (Getactivity (), (charsequence) Bundle.get ("Key"),1). Show (); } setlistadapter (NewArrayadapter<string> (Getactivity (), Android.    R.layout.simple_list_item_1, show)); }}
 PackageCom.example.fragmenttabhost;ImportAndroid.os.Bundle;Importandroid.support.v4.app.FragmentActivity;ImportAndroid.support.v4.app.FragmentTabHost; Public  class mainactivity extends fragmentactivity {    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Fragmenttabhost tabhost = (fragmenttabhost) Findviewbyid (R.id.tab); Tabhost.setup ( This, Getsupportfragmentmanager (), r.id.content); Tabhost.addtab (Tabhost.newtabspec ("Tab1"). Setindicator ("TAB1"), Myfragment.class,NULL); Bundle B =NewBundle (); B.putstring ("Key","I am TAB2"); Tabhost.addtab (Tabhost.newtabspec ("TAB2"). Setindicator ("TAB2", Getresources (). getdrawable (R.drawable.ic_launcher)), Myfragment.class, b); }}

Execution results


2. A better-looking demo, imitate the main page

Fragment Layout file Fragment_1,2,3,4,5.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" >             <ImageViewandroid:id= "@+id/imageview"android:layout_width="Fill _parent "android:layout_height=" Fill_parent "android:scaletype=" Fitcenter "  android:src="@drawable/mm1" >                                            </ImageView></linearlayout>

Tab_item_view.xmlbutton layout

<?

XML version= "1.0" encoding= "Utf-8"?><linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" android:layout_width =" wrap_content " android:layout_height =" wrap_content " android:gravity =" center " Android:orientation =; <ImageViewandroid:id="@+id/imageview"android:layout_width="Wrap _content "android:layout_height=" Wrap_content "android:focusable=" false " android:padding="3DP"android:src="@drawable/tab_home_btn"> </ImageView> <TextViewandroid:id= "@+id/textview"android:layout_width="Wrap_ Content "android:layout_height="wrap_content "android:text=" Home " Android:textsize="10sp"android:textcolor="#ffffff"> </TextView></linearlayout>

Main Page Layout Main_tab_layout.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:orientation="vertical" >                <framelayout  android:id< /span>= "@+id/realtabcontent"  android:layout_width< /span>= "fill_parent"  android:layout_height  =         "0dip"  android:layout_weight  = "1" />     <android.support.v4.app.fragmenttabhost  android:id  =" @android: Id/tabhost " android:layout_width  =" fill_parent " android:layout_height  =" wrap_content " android:background  =" @drawable/maintab_toolbar_bg " >         <framelayoutandroid:id="@android: Id/tabcontent"android:layout_width ="0DP"android:layout_height="0DP"android:layout_weight="0" />                                                                 </android.support.v4.app.FragmentTabHost></linearlayout>

Fragmentpage1,2,3,4,5.java Fragment Implementation

 PackageCom.vhreal.myfragmenttest;ImportCOM.VHREAL.MYFRAGMENTTEST.R;ImportAndroid.os.Bundle;ImportAndroid.support.v4.app.Fragment;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup; Public  class FragmentPage1 extends Fragment{    @Override     PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {returnInflater.inflate (R.layout.fragment_1,NULL); }   }

Main Page Implementation Maintabactivity.java

 PackageCom.vhreal.myfragmenttest;ImportCOM.VHREAL.MYFRAGMENTTEST.R;ImportAndroid.os.Bundle;Importandroid.support.v4.app.FragmentActivity;ImportAndroid.support.v4.app.FragmentTabHost;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.widget.ImageView;ImportAndroid.widget.TabHost.TabSpec;ImportAndroid.widget.TextView;/** * @author vhreal * Functional Descriptive narrative: Define yourself tabhost */ Public  class maintabactivity extends fragmentactivity {    //define Fragmenttabhost object    PrivateFragmenttabhost Mtabhost;//define a layout    PrivateLayoutinflater Layoutinflater;//Define an array to hold the fragment interface    PrivateClass fragmentarray[] = {fragmentpage1.class, fragmentpage2.class, Fragmentpage3.class, Fragmentpage4.class, F Ragmentpage5.class};//Define an array to hold the button picture    Private intMimageviewarray[] = {r.drawable.tab_home_btn, r.drawable.tab_message_btn, R.DRAWABLE.TAB_SELFINFO_BTN, R.DRAWABLE.TAB_SQUARE_BTN, r.drawable.tab_more_btn};the text of the// tab tab    PrivateString mtextviewarray[] = {"Home","Message","Friends","Square","A lot of other"}; Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (r.layout.main_tab_layout);    Initview (); }/** * Initializing components * /    Private void Initview() {//Instantiate Layout objectLayoutinflater = Layoutinflater.from ( This);//Instantiate Tabhost object, get TabhostMtabhost = (fragmenttabhost) Findviewbyid (Android.        R.id.tabhost); Mtabhost.setup ( This, Getsupportfragmentmanager (), r.id.realtabcontent);//Get the number of fragment        intCount = Fragmentarray.length; for(inti =0; I < count; i++) {//Set icons, text, and content for each TabbuttonTabspec Tabspec = Mtabhost.newtabspec (Mtextviewarray[i]). Setindicator (Gettabitemview (i));//Add Tabbutton into tab tabMtabhost.addtab (Tabspec, Fragmentarray[i],NULL);//Set the background of the TabbuttonMtabhost.gettabwidget (). Getchildat (i). Setbackgroundresource (R.drawable.selector_tab_background); }    }/** * Set icons and text for Tabbutton */    PrivateViewGettabitemview(intIndex) {View view = Layoutinflater.inflate (R.layout.tab_item_view,NULL);        ImageView ImageView = (ImageView) View.findviewbyid (R.id.imageview);        Imageview.setimageresource (Mimageviewarray[index]);        TextView TextView = (TextView) View.findviewbyid (R.id.textview); Textview.settext (Mtextviewarray[index]);returnView }}

Execution results

Iv. references
    • Android Fragment fragment simple introduction specific explanation
    • Android Fragment Basic Introduction
    • Android Fragment True Total parsing (up and down) must see

Android Fragment Simple Example

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.