Simple introduction and Create tabs for Android with fragment details

Source: Internet
Author: User

Fragment Essentials
    1. Fragment appears as part of the activity interface
    2. Multiple fragment can occur simultaneously in one activity, and a fragment may be used in multiple activity.
    3. During activity run, you can add, remove, or replace fragment (add (), remove (), replace ())
    4. Fragment can respond to their input events and have their own life cycles, of course, whose lifecycles are directly affected by the life cycle of the host activity to which they belong.
Design philosophy

Android introduced the concept of fragments in 3.0, primarily to support more dynamic and flexible UI designs on large-screen devices, such as tablets. Tablet screens are much larger than phones, have more room to put more UI components, and create more interaction between these components. Fragment allows such a design without requiring you to manage the complex changes of viewhierarchy in person. By dispersing the layout of the activity into fragment, you can modify the appearance of the activity at run time and save those changes in the back stack managed by the activity. (http://developer.android.com/ guide/topics/fundamentals/fragments.html)

For example, a news app can use a fragment on the left side of the screen to display a list of articles, and then use another fragment on the right side of the screen to show an article--2 a fragment side of the same activity, And each fragment has its own set of lifecycle callback methods and handles their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article in the same activity and read it:

Fragment should be a modular and reusable component in your application. That is, because fragment defines its own layout and defines its own behavior by using its own lifecycle callback method, you can include fragment in multiple activities. This is especially important because it allows you to adapt your user experience to a different screen size. For example, you might have more than one fragment in an activity when the screen size is large enough, and when this is not the case, another individual is started, Use different fragment of activity.

To continue the example of the previous news-when running on a particularly large screen (such as a tablet), the app can embed 2 fragment in activity A. However, on a normal-sized screen (such as a mobile phone), there is not enough space for 2 fragment, so Activity A will only contain the fragment of the article list, and when the user selects an article, it will start Activityb, It contains the fragment to read the article. As a result, applications can support 2 design patterns in the same way.

Create Fragment to create a Fragment, you must create a subclass of Fragment (or inherit from a subclass of it that already exists). The code for the Fragment class looks much like Activity. It contains callback methods similar to activity, such as OnCreate (), OnStart (), OnPause (), and OnStop (). In fact, if you're going to switch from an off-the-shelf Android app to using fragment, you can simply move the code from your activity's callback method to your fragment callback method.

In general, you should implement at least the following life cycle methods:

    • OnCreate ()
      The system calls this method when fragment is created.
      In the implementation code, you should initialize the necessary components that you want to keep in fragment, which can be resumed when fragment is paused or stopped.
    • Oncreateview ()
      This method is called by the system fragment the first time it is drawn to its user interface. In order to draw the fragment UI, this method must return a view, which is the root view of your fragment layout. If fragment does not provide a UI, you can return null.
    • OnPause ()
      When the user is about to leave fragment, the system calls this method as the first indication (however it does not always mean that fragment will be destroyed.) Before the end of the current user session, you should usually submit any changes that should persist here (because the user might not return).
The chart of its life cycle is as follows:

Most applications should implement at least 3 of these methods for each Fragment, but there are other callback methods you should use to deal with the various stages of the Fragment life cycle. The entire lifecycle callback method will be handlingthe in the later chapters Fragment discussed in Lifecycle.

In addition to inheriting the base class Fragment, there are some subclasses that you might inherit:

    • Dialogfragment
      Displays a floating dialog box.
      Using this class to create a dialog box is a good choice to use outside of the dialog tool method of the activity class,
      Because you can merge a fragment dialog box into the activity-managed fragment back stack, allowing the user to return to a fragment that was previously discarded.
    • Listfragment
      Displays a list of items that are managed by a adapter (for example, Simplecursoradapter), similar to listactivity.
      It provides methods to manage a list view, such as a Onlistitemclick () callback to handle a click event.
    • Preferencefragment
      Displays a list of hierarchies for a preference object, similar to preferenceactivity.
      This is useful when creating a "set up" activity for your app.
    All
      right, it's all official. I'm not going to say much, just on my fragment. Create a tab in detail:
      mainactivity
ImportCom.menglifang.frag.FragmentOne;ImportCom.menglifang.frag.FragmentTwo;ImportCom.menglifang.frag.Fragmentfour;ImportCom.menglifang.frag.Fragmentfree;ImportAndroid.os.Bundle;Importandroid.support.v4.app.FragmentActivity;ImportAndroid.support.v4.app.FragmentManager;Importandroid.support.v4.app.FragmentTransaction;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;Importandroid.widget.FrameLayout;Importandroid.widget.LinearLayout;ImportAndroid.widget.TextView; Public classMainactivityextendsFragmentactivityImplementsonclicklistener{framelayout framelayout;    TextView TEXT1,TEXT2,TEXT3,TEXT4;     Fragmentmanager FM; Privatefragmenttransaction ft; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Framelayout=(framelayout) Findviewbyid (R.id.frag_view); Text1=(TextView) Findviewbyid (R.id.tab_one); Text2=(TextView) Findviewbyid (r.id.tab_two); Text3=(TextView) Findviewbyid (R.id.tab_free); Text4=(TextView) Findviewbyid (R.id.tab_four); Text1.setonclicklistener ( This); Text2.setonclicklistener ( This); Text3.setonclicklistener ( This); Text4.setonclicklistener ( This); FM= This. Getsupportfragmentmanager (); FT=fm.begintransaction (); Ft.replace (R.id.frag_view,NewFragmentone ());            Ft.commit (); } @Override Public voidOnClick (View arg0) {ft=fm.begintransaction (); Switch(Arg0.getid ()) { Caser.id.tab_one:ft.replace (R.id.frag_view,NewFragmentone ());  Break;  Caser.id.tab_two:ft.replace (R.id.frag_view,Newfragmenttwo ());  Break;  Caser.id.tab_free:ft.replace (R.id.frag_view,NewFragmentfree ());  Break;  Caser.id.tab_four:ft.replace (R.id.frag_view,NewFragmentfour ());  Break;    } ft.commit (); }    }

Created four fragement: For the sake of simplicity my four fragment each fragement is the same as the respective layout file is different

ImportCOM.MENGLIFANG.FRAGMENT.R;ImportAndroid.os.Bundle;Importandroid.support.v4.app.Fragment;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup; Public classFragmentoneextendsfragment{@Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {//TODO auto-generated Method StubView View=inflater.inflate (R.layout.fragone,NULL); returnView//Super.oncreateview (Inflater, container, savedinstancestate);    }}

Layout file: Give only the layout in mainactivity and a layout in a fragment

Layout in mainactivity: Activity_main.xml

<Relativelayoutxmlns: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 " ><LinearLayoutAndroid:id= "@+id/tab"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:orientation= "Horizontal">    <TextViewAndroid:id= "@+id/tab_one"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_weight= "1"Android:text= "Latest News"/>    <TextViewAndroid:id= "@+id/tab_two"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_weight= "1"Android:text= "Hot News"/>    <TextViewAndroid:id= "@+id/tab_free"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_weight= "1"Android:text= "Social News"/>    <TextViewAndroid:id= "@+id/tab_four"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_weight= "1"Android:text= "Liverpool News"/></LinearLayout>   <Framelayoutandroid:orientation= "vertical"Android:id= "@+id/frag_view"Android:layout_below= "@+id/tab"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"Android:background= "#ffff00"></Framelayout></Relativelayout>

A fragment layout: Fragone.xml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "200DP"android:orientation= "vertical" >    <TextViewAndroid:background= "#ff0000"android:gravity= "Center"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:text= "This is the first Frage"/></LinearLayout>

In fact, this column is very simple, a look at the basic understanding, I checked on the internet, a lot of people are to take the official website of the copy down, I think the real sample is easier to understand

Many have insufficient to welcome everybody to study the exchange

Simple introduction and Create tabs for Android with fragment details

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.