Foreword
After learning Java and Android for nearly a year, the results of the period should be to independently complete a Android client and ensure the stability of its main line version. During the period, I encountered a lot of pit, and I also learned a lot of Android knowledge with my brother. But people always have to embrace changes and not make themselves too comfortable. Although I am reluctant, I have proved my learning ability. The next step is to start doing ROM Porting. Here we summarize the most fragments used in the previous items.
Introduction to Fragment
Fragment can be understood as a behavior or part of the user interface in Activity, and it must be nested in Activity. But a Fragment has its own independent XML layout file and has good packaging. Therefore, Fragment can be easily replaced with Activity under special cases.
Create Fragment
Create a Fragment and create an Activity. It is necessary to implement the XML layout file and Java Class.
The XML layout files are the same as other layout files. For example, the layout files shown below (Fragment_layout.xml):
<? xml version = "1.0" encoding = "UTF-8"?> <linearlayout xmlns: Android = "http://schemas.android.com/apk/android" android: layout_width = "MATCH_PARENT" Android: layout_height = "MATCH_PAREAT" Android: Orientation = "Vertical"> <textView android: ID = "@+ID/textView" android: layout_width = "wrap_content" android: la Yout_height = "wrap_content" android: text = "@string /testView" / / > <Button android: ID = "@+ID/Button" Android: Layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "@string /Button " /> < /linearlayout>
In Java code, in general, the following life cycle methods can be implemented as needed: Fragment:
1. Onattach (): When the Fragment depends on Activity, you can get the Activity handle in this method to achieve communication between the Fragment and Activity.
2. Oncreate (): initialize the frame.
3. OncreateView (): The system calls this method when drawing the user interface for the first time for Fragment.
4. OnActivityCreated (): After being executed by the host Activity Oncreate function, you can perform Fragment's own Widget instance and business logic processing in this method.
5. OnDestoryView (): Call when the frame starts to be destroyed.
6. OnStart (): Call when Fragment can be visible.
There are also many other callback functions that are used to manipulate the Fragment life cycle. You can learn from Google by yourself.
Fragment life cycle
Each Fragment has its own set of life cycle callback methods and handle its own user input events. The corresponding life cycle is shown in the figure below:
Add Fragment to Activity
First of all, you need to ensure that Acitivity supports Fragment, so Activity usually needs to inherit from FragmentActivity. There are usually two methods to add Fragment to Activity: static and dynamic.
Static method adds Fragment directly to the XML layout file of Activity, as shown below:
<? xml version = "1.0" encoding = "UTF-8"?> <linearlayout xmlns: Android = "http://schemas.android.com/apk/android" android: layout_width = "MATCH_PARENT" Android: layout_height = "MATCH_PAREANT" Android: Baselinealigned = "False" Android: Orientation = "Horizontal"> <Fragment android: ID = "@+ID/First" android: name = "com. Example.fristFragment "android: layout_width =" 0dp " Android: layout_height = "match_parent" android: layout_weight = "1" /> <Fragment android: ID = "@+ID /second" android: name = "com.example.se condfragment "android: layout_width =" 0dp "android: layout_height = "MATCH_PARENT" Android: layout_weight = "1" /> < /linearlayout>
When the Android: name attribute in <fragment> specifies the instantiated Fragment class in the layout, when the Activity layout is created, it instantiated each frame in the layout file and calls them to call them to obtain each to obtain each. A Fragment layout. The system directly inserts the View returned by the <fragment> element location
Note: Each fragment requires a unique identification. If restarting Activity, the system can be used to restore the Fragment (and to capture the transaction processing of Fragment, such as removing). There are three ways to provide IDs for Fragment: There are three ways:
Dynamic method
Use Fragmenttranscation. You can use the API of Fragmenttranscation to operate the Fragment of Activity (such as adding, removing, or replacing Fragment). The reference code is as follows:
FragmentManager FragmentManager = getFragmentManager () Fragmenttransaction Fragmenttraction = FragmentManager.begintraction (); ExampleFragment Frag MENT = New ExampleFragment (); Fragmenttransaction.add (R.id.fragment_Container, Fragment); fragmentTransaction.commit ();
The first parameter of the ADD () function is the ViewGroup of the Fragment, which is specified by the resource ID (Resource ID). The second parameter is the fragment to be added. Once changed through Fragmenttranscation, it should take effect with Commit () visual changes.
Fragments communication
Fragments should not be directly communicated, and interaction between them should be performed through the host Activity. There are three ways to interact with Fragment and Acitivity:
1. Activity creates a Fragment with parameters.
2. Activity maintains the object handle of the Fragment, which can be directly called the Public method of the Fragment through the handle.
3. Fragment can obtain the defined Listener handle in the onattach function.
Create the frame with parameters
In some specific cases, Fragment may require specific parameters to initialize. Since Fragment must have only one ginseng constructor, you can consider using the static Newinstance method to create a Fragment with parameters. The example code is as follows:
Import Android.os.Bundle; Import Android.support.v4.app.fragment; Public Class Testfragment Extends Fragment {Public Static Testfragment (int Num, String Title) {testfragment fragment = new testfragment (); bundle args = New Bundle ( );; "Num", Num); args.putString ("title", title); fragment.Setarguments (ARGS); Return Fragment;} @Override Public Void (Bublic void ndle Savedancestate) {Super.onCreate (Savedinstancestate ).; You can simply load a parameter with parameters in Activity:
Fragmenttransaction ft = GetSupportfragmentManager (). Begintraction (); Testfragment Fragment = TESTFRAGMENT.NEWINTANCE (5, "Fragment Title"); ACE (R.id.Placeholder, Fragment); ft.Commit ();
The method of calling fragment
Because Activity can get the embedded Fragment handle, this method can be called directly through the Fragment handle.
Public Class Testfragment Extends Fragment {Public Void Dosomething (String Param) {// Do Something in Fragment}}} In Activity, you can call this method directly through the object handle of the Fragment:
Public Class Mainaction Extends FragmentActivity {@Override Public Void Oncreate (Bundle Savedancestate) {Super.Oncreate (SAVEDINCESTATE); TESTFR. agment testfragment = new testfragment (); testfragment.dosomething ("some paras");}} Fragment Listener
If Fragment needs to share events to Activity, this method needs to be used. Fragment defines an interface, and this interface is implemented by Activity. The Activity of the interface will be achieved in the onattach () method.
The defined interface code in Fragment is as follows:
Import Android.support.v4.app.fragment; Public Class MyListFragment Extends Fragment {// ... // Define the Listener Type // Listener Is the Act. Ivity itset prive onItemselectEdlistener Listener; // Define the events that the frame Will use to make communicate public interface onItemselectListener {Public Void OnrsesItemselect (String link);} // Store The Listener (Activity) That will Have Events Fired Once the Fragment is Attached @Override Public Void Onattach (Activity Activity) {Super.onattach (Activity ); Activity Instanceof onItemSelectEdlistener) {Listener = (onItemselectListener) Activity;} Else {Throw New ClassCastexception (Activity.TO String () + "Must iMustFragment.onItemselectListener"); User SELECTS SOMETHING in the Fragment Public Void ONSOMECLICK (View v) {Listener.onrsSItemselect ("SOME LINK");}}Implement this interface in Activity:
Import Android.Support.v4.app.fragmentActivity; Public Class RSSFEEDATITITITY Extends FragmentActivity Implements MyListFragment.oniteMSELECTED Listener {Detailfragment Fragment; @Override ProteCted Void Oncreate out.Activity_rssfeed); Fragment = (Detailfragment) GetSupportfragmentManager () .findFragmentByid (R.id.detailfragment);} // now we can define the action in the activ it when the fragment event files @Override Public Void OnrsesItemselect (String Link) {if (Fragment ! = Null && fragment.isinlayout ()) {fragment.settext (link);}}}