Android Practice Notes (4) --- basic concepts of Fragment,
Android Practice Notes (4) --- basic concepts of Fragment
For more information, see coder-pig.
Fragment I believe everyone will be familiar with it, slide side, drawer effect, DialogFragment, etc.
Fragment is used. The basic concepts of Fragment have been described in the previous article. I will review it here,
Let's learn about new things and review them with Google's official api!
1) What is Fragment and its lifecycle:
Key points:
1) introduced after version 3.0, that is, minSdk must be later than 11
2) Fragment needs to be nested in the Activity. Of course, it can also be nested in another Fragment, but this is nested.
Fragment also needs to be nested in the Activity. Indirectly, Fragment still needs to be nested in the Activity !! Host
Of course, he also has his own life cycle! We do not recommend nesting Fragment in Fragment.
Because the lifecycle of Fragment nested in it is uncontrollable !!!
3) according to the official documentation, at least three methods are required for creating Fragment: onCreate (), onCreateView (), and OnPause ();
However, it seems that it is okay to write only one onCreateView...
4) the lifecycle of Fragment is similar to Activity: three states:
Resumed: In the allowed Fragment visible Paused: The Activity is visible, but the focus is not obtained.
Stoped:
① Call addToBackStack () and Fragment is added to the Bcak Stack
② The Activity is switched to the background, or the Fragment is replaced/deleted.
Ps: The fragment in the stopped state is still alive (all States and member information are maintained by the system). However, it
Invisible, and if the activity is killed, it will also be killed.
5) Fragment sub-classes include:
Dialog Box: DialogFragment list: ListFragment
Option setting: PreferenceFragmentWebView Interface:WebViewFragment
2) How to Create a Fragment?
① Add Fragment statically
Step 1: Define the Fragment layout, that is, the fragment display content
Step 2: Customize a Fragment class. You must inherit Fragment or its subclass and override the onCreateView () method.
Call the inflater. inflate () method to load the layout file of Fragment, and then return the loaded view object.
public class Fragmentone extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment1, container,false);return view;}}
The parameters are: fragment layout to be loaded; the parent ViewGroup of the loaded fragment; and the third parameter is:
Whether to add the parent ViewGroup to the Root View of the layout file. However, a redundant ViewGroup may be generated.
Object. If you do not understand it here, you can simply write false.
In addition, the inflate method has other forms. A typical one is direct inflate (to display the layout, null ),
If this is used, the layout_XX attribute of the Root View in the item layout will be ignored and set to the default package.
Content, so we recommend that you use the inflate () parameter! For details, refer:
Http://www.2cto.com/kf/201407/313054.html
Step 3: add the Fragment tag to the layout file of the Activity to which fragment is to be loaded,
Remember, the name attribute is a fully qualified class name, that is, the package name containing Fragment, for example:
<fragment android:id="@+id/fragment1" android:name="com.jay.example.fragmentdemo.Fragmentone" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
Step 4: The Activity calls setContentView () in the onCreate () method to load the layout file!
② Dynamically add Fragment
Step 1: Call getFragmentManager to obtain the FragmentManager object fm
Step 2. fm calls the beginTransaction () method to obtain the Fragment transaction object bt
Step 3: bt calls add () to add or relpace () to replace Fragment. The parameters are the same.
The first parameter is the container to be passed in, and the second parameter is the Fragment object.
Step 4: Finally, you need to call bt. commit () to commit the transaction, except for the add and replace methods.
There is also a remove method to remove Fragment, which also requires commit!
Partial code:
Fragment1 f1 = new Fragment1();getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f1).commit();
Ps: the code here is the use of fragment under the app package, so the imported Fragment-related packages are all app !!!
You can also use the v4 package for lower version compatibility. For more information, see:
Detailed explanation of Fragment app package or v4 package
3) interaction between Fragment and Activity ① component acquisition:
Fragment:
GetActivity (). findViewById (R. id. list)
Activity obtains the components in Fragment (either by id or tag ):
GetFragmentManager. findFragmentByid (R. id. fragment1 );
② Data Transmission
1. Activit transmits data to Fragment:
Create a Bundle data packet in the Activity and call setArguments (bundle) of the Fragment instance)
In this way, the Bundle packet is sent to Fragment, and then getArguments is called in Fragment to obtain
Bundle object, and then parse it.
2. Fragment transmits data to Activity
Define an internal callback interface in Fragment, and then let the Activity containing the Fragment implement the callback interface,
Fragment can transmit data through the callback interface. It is believed that many people know what it is,
I can't write it out. The one hundred-degree online "fragment transfers data to Activity" is all the code from instructor Li Gang. It's really speechless.
Forget it. Write down some code here. I believe the reader will understand it at a Glance:
Step 1: Define a callback interface: (Fragment)
/* Interface */public interface CallBack {/* defines a method for obtaining information */public void getResult (String result );}
Step 2: interface callback (in fragment)
/* Interface CallBack */public void getData (callBack CallBack) {/* Get the information of the text box. Of course, you can also pass other types of parameters, see the requirement. */String msg = editText. getText (). toString (); callBack. getResult (msg );}
Step 3: Use the interface callback method to read data (in Activity)
/* Use the interface callback method to obtain data */leftFragment. getData (new CallBack () {@ Override public void getResult (String result) {/* print information */Toast. makeText (MainActivity. this, "-->" + result, 1 ). show ();}});
To sum up, it is
-> Define an interface in Fragment to define abstract methods. What type of data do you Want to transmit?
The parameter specifies the type of the parameter;
-> Next, write an abstract method in the calling interface to pass the data to be passed.
-> The Activity is followed by calling the method provided by Fragment, and then rewriting the abstract method for data.
Read !!!
3. data transmission by Fragment and Fragment
In fact, this is very simple. Find the fragment object to accept the data and directly call setArguments to transfer the data.
Generally, data is transmitted when the fragment is redirected. You only need to initialize the Fragment to be redirected.
And then call the setArguments method to pass in the data!
The Code is as follows:
FragmentManager fManager = getSupportFragmentManager( );FragmentTransaction fTransaction = fManager.beginTransaction();Fragmentthree t1 = new Fragmentthree();Fragmenttwo t2 = new Fragmenttwo();Bundle bundle = new Bundle();bundle.putString("key",id);t2.setArguments(bundle); fTransaction.add(R.id.fragmentRoot, t2, "~~~"); fTransaction.addToBackStack(t1); fTransaction.commit();
If two Fragment requests require immediate data transfer instead of redirection, you must first obtain the data transmitted from f1 in the Activity and then transmit the data.
To f2
4) Fragment management and Fragment transactions: ① management:
Activity management Fragment mainly relies on FragmentManager to call findFragmentById () to obtain the specified fragment
You can also call the popBackStack () method to bring up the background Fragment; or you can call addToBackStack (null) to join the stack.
Or listen for changes in the background Stack: addOnBackStackChangeListener
② Transactions
If you want to add, delete, and replace Fragment, you need to use the FragmentTransaction object;
After executing the Fragment operation, remember to use the commit () method to submit the transaction!
5) last few words:
I believe that you can't remember the above life cycle chart at half past one. Let's talk about the general process at the beginning:
① When the Activity loads Fragment, it calls the following methods in sequence:
OnAttach-> onCreate-> onCreateView-> onActivityCreated-> onStart-> onResume;
② When we create a floating dialog box-style Activity, or others, we can make the Activity where Fragment is located visible, but do not get the focus.
OnPause
③ When the dialog box is closed, the Activity gets the focus again:
OnResume
④ When we replace Fragment and call addToBackStack () to add it to the Back Stack
OnPause-> onStop-> onDestoryView
Note that the Fragment has not been destroyed !!!
⑤ When we press the keyboard's return key, Fragment will display it again:
OnCreateView-> onActivityCreated-> onStart-> onResume;
⑥ If the addToBackStack () method is not called before the transaction commit after we replace
If Fragment is added to the back stack or the Activity is exited, Fragment will be completely ended,
Fragment enters the destruction status
OnPause-> onStop-> onDestoryView-> onDestory-> onDetach