Talk about Android fragments detailed use _android

Source: Internet
Author: User
Tags static class stub

Fragments was born in the original

Since the introduction of the fragments concept in Android 3.0, the translation of the word Sea can be translated as fragments, fragments. It is designed to address the dynamic and flexible UI design for different screen resolution. Large screens such as flat-panel screens such as mobile phones, the tablet is designed to allow more room for more UI components, and the extra space for the UI makes it more interactive, giving birth to fragments. Fragments's design does not require you to personally manage the complex changes of view hierarchy, by dispersing the layout of the activity into frament, you can modify the appearance of the activity at run time, and the back stack managed by the activity To save some of the changes.

Fragments design Concept

When designing applications, especially Android apps, there are many resolutions to adapt, and fragments allows you to dynamically manage the UI on different screens of the screen. For example: the Communication Application (QQ), the user list can be on the left, the message window on the right side of the design. And in the Mobile screen user list fill screen when you click on a user, the pop-up dialog window design, the following figure:

The life cycle of fragments

Each fragments has its own set of lifecycle callback methods and handles its own user input events. The corresponding life cycle can refer to the following figure

Most of these programs must use the three callback methods that fragments must implement, respectively:

OnCreate

Called when the system creates fragments, it can perform initialization work or be used to restore state when the program is paused or stopped, as in the activity of OnCreate.

Oncreateview

The callback method for the first drawing of the user interface must return the fragments view UI to be created. If you do not want to provide the fragments user interface, you can return null.

OnPause

When the user leaves this fragments call, then you have to submit any changes that should be lasting because the user may not come back. More events can refer to the life cycle diagram of the above diagram.

Categories of fragments

There are three kinds of fragments in the system, these three kinds of fragments have different application scenarios respectively:

Dialogfragment

Dialog-box fragments, you can put a fragments dialog box into the fragments back stack of activity management, allowing the user to return to a previous rejection of fragments.

Listfragments

Similar to the listactivity effect, and also provides listactivity similar onlistitemclick and Setlistadapter functions.

Preferencefragments

Similar to preferenceactivity. You can create an ipad-like setup interface.

Detailed use of fragments

First look at a demo effect chart:

On the left click, the character on the right will be the same as the character of the item selected on the left. Similar to the Setup interface on the ipad, does this draw on the ipad's UI?

An XML file that is relative:

<?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= "Horizontal" >

  <fragment class= "Com.xuzhi.fragment.fragmentdemoactivity$titlesfragment" Android:id= "@+id/titles" android:layout_weight= "1"
    android:layout_width= "0px" android:layout_height= "Match_" Parent "
    />
  
  <framelayout android:id=" @+id/details "android:layout_weight=" 1 "android:layout_width=" 0px "android:layout_height=" match_parent "
    android:background="? Android:attr/detailselementbackground "
    ></FrameLayout>
</LinearLayout>

Main interface code (comments already):

Package com.xuzhi.fragment;
Import android.app.Activity;
Import Android.app.AlertDialog;
Import android.app.Fragment;
Import android.app.FragmentTransaction;
Import android.app.ListFragment;
Import Android.os.Bundle;
Import Android.util.TypedValue;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.ArrayAdapter;
Import Android.widget.ListView;
Import Android.widget.ScrollView;

Import Android.widget.TextView; public class Fragmentdemoactivity extends activity {public static string[] Array = {"Text1,", "Text2", "Text3", "Tex

   T4 "," Text5, "," Text6 "," Text7 "," Text8 "}; /** called the activity is a. 
     * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
   Setcontentview (R.layout.main);
     public static class Titlesfragment extends Listfragment {boolean mdualpane;
     
     int mcurcheckposition = 0;
@Override     public void OnCreate (Bundle savedinstancestate) {//TODO auto-generated Method stub super.oncreate (save
       Dinstancestate);
     System.out.println ("Fragment-->oncreate"); @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedin
       Stancestate) {//TODO auto-generated Method Stub System.out.println ("Fragment-->oncreateview");
     Return Super.oncreateview (Inflater, container, savedinstancestate);
       @Override public void OnPause () {//TODO auto-generated Method Stub super.onpause ();
     System.out.println ("Fragment-->onpause");
       
       @Override public void OnStop () {//TODO auto-generated Method Stub super.onstop ();
     System.out.println ("Fragment-->onstop"); @Override public void Onattach (activity activity) {//TODO auto-generated method stub Supe R.onattACH (activity);
     System.out.println ("Fragment-->onattach");
       @Override public void OnStart () {//TODO auto-generated Method Stub Super.onstart ();
     System.out.println ("Fragment-->onstart");
       @Override public void Onresume () {//TODO auto-generated Method Stub super.onresume ();
     System.out.println ("Fragment-->onresume");
       @Override public void OnDestroy () {//TODO auto-generated Method Stub Super.ondestroy ();
     System.out.println ("Fragment-->ondestroy"); @Override public void onactivitycreated (Bundle savedinstancestate) {//TODO auto-generate
       D method Stub super.onactivitycreated (savedinstancestate);
       System.out.println ("fragment-->onactivitycreted"); Setlistadapter (New arrayadapter<string> (getactivity), Android.

       R.layout.simple_list_item_1, array)); View Detailsframe = Getactivity (). Findviewbyid (R.id.details);

       Mdualpane = Detailsframe!= null && detailsframe.getvisibility () = = view.visible;
      if (savedinstancestate!= null) {mcurcheckposition = Savedinstancestate.getint ("Curchoice", 0);//Remove data from saved state

         } if (Mdualpane) {Getlistview (). Setchoicemode (Listview.choice_mode_single);
       ShowDetails (mcurcheckposition); 
      @Override public void Onsaveinstancestate (Bundle outstate) {//TODO auto-generated a stub

       Super.onsaveinstancestate (outstate); Outstate.putint ("Curchoice", mcurcheckposition);//Save the current subscript} @Override public void Onlistitemclick (ListView L, View v, int position, long ID) {//TODO auto-generated Method Stub Super.onlistitemclick (l, V, position,
       ID);
     ShowDetails (position); 
       } void ShowDetails (int index) {mcurcheckposition = index; if (Mdualpane) {getListView (). setitemchecked (index, true); 
         Detailsfragment details = (detailsfragment) Getfragmentmanager (). Findfragmentbyid (R.id.details); if (details = null | | details.getshownindex ()!= index) {details = Detailsfragment.newinstance (mcurcheckposit 

           ION); 
           Get a fragment transaction (like a sqlite operation) fragmenttransaction ft = Getfragmentmanager (). BeginTransaction (); Ft.replace (r.id.details, details)//replaces the resulting fragment with the current ViewGroup content, add does not replace the ft.settransition (frag Menttransaction.transit_fragment_fade);//Set animation effect Ft.commit ()//Submit}} else {new Alertdia Log. Builder (Getactivity ()). Settitle (Android. R.string.dialog_alert_title). Setmessage (Array[index]). Setpositivebutton (Android.
       R.string.ok, NULL). Show (); /** * As part of the interface, provide fragment with a layout * @author Terry */public static class DETAILSFRAGM EnT extends Fragment {public static detailsfragment newinstance (int index) {detailsfragment details = new De
       Tailsfragment ();
       Bundle args = new Bundle ();
       Args.putint ("index", index);
       Details.setarguments (args);
     return details;
     public int Getshownindex () {return getarguments (). GetInt ("index", 0); @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedinstanc

       Estate) {//TODO auto-generated Method stub if (container = null) return null;
       ScrollView scroller = new ScrollView (getactivity ());

       TextView Text = new TextView (getactivity ()); int padding = (int) typedvalue.applydimension (Typedvalue.complex_unit_dip, 4, getactivity (). GE
       Tresources (). Getdisplaymetrics ());
       text.setpadding (padding, padding, padding, padding);

       Scroller.addview (text); Text.settext (Array[getshownindex ()]);
     return scroller;

 }
   }
 }

Attention:

1. If you want to create a menu inside the fragment, you must set the OnCreate to exist Optionmenu before you can create it, the code is:

public static class Detailsfragment extends Fragment {

     @Override public
     void OnCreate (Bundle savedinstancestate ) {
       //TODO auto-generated method Stub
      super.oncreate (Savedinstancestate);
       Sethasoptionsmenu (True);
     }
 

The following operation can be as normal as the menu usage of Android, the code is:

@Override public
     void Oncreateoptionsmenu (Menu menu, Menuinflater inflater) {
       //TODO auto-generated method stub
      Super.oncreateoptionsmenu (menu, inflater);
       Menu.add ("Menu 1a"). Setshowasaction (menuitem.show_as_action_if_room);
         Menu.add ("Menu 1b"). Setshowasaction (Menuitem.show_as_action_if_room);
     }
     
     @Override Public
     Boolean onoptionsitemselected (MenuItem item) {
       //TODO auto-generated method stub
      Toast.maketext (Getactivity (), "Index is" +getshownindex () + "&& menu text are" +item.gettitle (), 1000). Show ();
       return super.onoptionsitemselected (item);
     }

Demo Download: Android Framentdemo

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.