Android and androidsdk
Lifecycle
Because Fragment must be embedded in Acitivity, the lifecycle of Fragment is closely related to its Activity.
If the Activity is paused, all Fragment is paused. if the Activity is stopped, all Fragment in the Activity cannot be started. If the Activity is destroyed, all Fragment in it will be destroyed.
However, when the Activity is active, you can independently control the Fragment status, such as adding or removing Fragment.
When performing the fragment transaction (conversion), you can put the fragment intoBack stackSo that the user can perform the return operation.
Use
When using Fragment, You need to inherit the Fragment or Fragment subclass (DialogFragment, ListFragment, PreferenceFragment, WebViewFragment), so the Fragment code looks similar to the Activity.
- Three required callback Functions
OnCreate ()
The system calls this method when creating Fragment. The related components should be initialized here, and some items should be retained even when they are paused or stopped.
OnCreateView ()
When the system calls this method when drawing the Fragment UI for the first time, a View must be returned. If Fragment does not provide the UI, null can be returned.
NOTE: If it is inherited from ListFragment, the default Implementation of onCreateView () will return a ListView, so you do not need to implement it yourself.
OnPause ()
When the user leaves Fragment, the first call of this method requires some changes, because the user may not return any more.
- Implement the Fragment UI
Provides the Fragment UI. The onCreateView () method must be implemented.
If the layout settings of Fragment are written in the example_fragment.xml resource file, the onCreateView () method can be written as follows:
public class ExampleFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.example_fragment, container, false); }}
The container parameter in onCreateView () represents the parent control of the Fragment in the Activity. The savedInstanceState provides the data of the previous instance.
Three parameters of the inflate () method:
The first is the resource ID, indicating the resource file corresponding to the current Fragment;
The second parameter is the parent container control;
The third Boolean parameter indicates whether to connect the layout and its parent container control. In this case, it is set to false because the layout has been inserted to the parent control, if this parameter is set to true, an additional View Group is generated.
Add Fragment to Activity
When Fragment is added to the Activity, it is in the corresponding View Group.
Fragment has two loading methods: one is to use the label <fragment> declaration in layout of the Activity, and the other is to add it to a specified ViewGroup in the code.
In addition, Fragment can not be any part of the Activity layout. It can be an invisible part. This part is skipped first.
- Loading Method 1: Add Fragment to Activity through the layout file of Activity
In the Activity layout file, add Fragment as a sub-tag.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.news.ArticleReaderFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /></LinearLayout>
The android: name attribute fills in the complete Class name of the fragment you have created.
When the system creates a layout file for this Activity, the system will instantiate each fragment and call their onCreateView () method to obtain the layout of the corresponding fragment, insert the returned value to the location where the fragment tag is located.
There are three methods to provide ID for Fragment:
Android: id property: Unique id
Android: tag attribute: unique string
If neither of the above is provided, the system uses the container view ID.
- Loading Method 2: Add Fragment to a ViewGroup by programming
When the Activity is in the Running state, you can dynamically add Fragment to the layout of the Activity. You only need to specify the parent View Group to add the Fragment.
First, you need a FragmentTransaction instance:
FragmentManager fragmentManager = getFragmentManager()FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
(Note: If you import android. support. v4.app. FragmentManager; FragmentManager = getSupportFragmentManager ();)
Then, use the add () method to add the Fragment object:
ExampleFragment fragment = new ExampleFragment();fragmentTransaction.add(R.id.fragment_container, fragment);fragmentTransaction.commit();
The first parameter is the container of the fragment, that is, the parent control group.
Finally, you need to call the commit () method to make the change of the FragmentTransaction instance take effect.
FragmentManager
To manage fragments in an Activity, you need to use FragmentManager. To get it, you need to call the getFragmentManager () method in the Activity.
Because the FragmentManager API was introduced in Android 3.0, that is, API level 11, for earlier versions, FragmentActivity in the support library should be used and the getSupportFragmentManager () method should be used.
Jobs that can be done with FragmentManager include:
Get the fragment in the Activity:
Use the findFragmentById () or findFragmentByTag () method.
Bring back stack to fragment:
PopBackStack (): The last fragment conversion in back stack is displayed. If no stack exists, false is returned.
This function is asynchronous: It adds the pop-up stack request to the queue, but this action will not be executed until the application returns to the event loop.
Add a listener to the back stack:
AddOnBackStackChangedListener ()
Transactions
When using Fragment, you can perform some actions through user interaction, such as adding, removing, and replacing. All these changes constitute a set, which is called a transaction.
You can call the method in FragmentTransaction to process this transaction, and store the transaction in the back stack managed by the activity. This allows you to perform the rollback operation of the fragment change.
FragmentManager fragmentManager = getFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Each transaction is a set of changes executed at the same time.
Use the add (), remove (), replace () Methods to add all the required changes, and then call the commit () method to apply these changes.
Before the commit () method, you can call addToBackStack () to add the transaction to the back stack. The back stack is managed by the activity. When you press the return key, the status of the last fragment is returned.
For example, the following code replaces the previous fragment with a new fragment, and stores the previous status in the back stack.
// Create new fragment and transactionFragment newFragment = new ExampleFragment();FragmentTransaction transaction = getFragmentManager().beginTransaction();// Replace whatever is in the fragment_container view with this fragment,// and add the transaction to the back stacktransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();
In this example, newFragment will replace fragment in the R. id. fragment_container container. If not, a new fragment will be added directly.
By calling addToBackStack (), a series of transformations of commit () are stored as a transaction in the back stack. you can press the Back key to return the status before the previous conversion.
When you remove a fragment, if addToBackStack () is not called before commit (), the fragment will be destroyed; If addToBackStack () is called, the fragment will be stopped, you can use the return key to restore data.
Commit
Calling the commit () method does not immediately execute the change action contained in the transaction. The commit () method adds the transaction to the UI thread queue of the activity. However, if necessary, you can call the executePendingTransactions () method to immediately execute the transaction provided by commit. This is usually unnecessary unless the transaction is depended on by other threads.
Note: You can only call commit () before the activity stores its status (when the user wants to leave the activity). If you call commit () after the storage status, an exception is thrown. This is because the status after commit is lost when the activity is restored again. If it is lost, use the commitAllowingStateLoss () method.
Interaction between Fragment and Activity
Fragment can use the getActivity () method to obtain the Activity instance, and then call methods such as findViewById.
View listView = getActivity().findViewById(R.id.list);
Note that when getActivity () is called, fragment must be associated with the activity (attached to an activity); otherwise, a null value is returned.
Similarly, an activity can obtain a reference to fragment and call the method in fragment. To obtain the reference of fragment, use FragmentManager, and then callFindFragmentById ()OrFindFragmentByTag ().
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
Create Event Callback
In some cases, fragment and activity sharing events may be required. A good practice is to define a callback interface in fragment and then require the host activity to implement it.When an activity receives a callback through this interface, it can share this information with other fragment in the layout.
For example, A news display application has two fragment items in an activity, one fragment A shows the list of Article topics, and the other fragment B shows the article. Therefore, when an article is selected, fragment A must notify activity, and then activity notifies fragment B to display this article.
In this case, define an OnArticleSelectedListener interface in fragment:
public static class FragmentA extends ListFragment { ... // Container Activity must implement this interface public interface OnArticleSelectedListener { public void onArticleSelected(Uri articleUri); } ...}
The activity that contains this fragment then implements the OnArticleSelectedListener interface and notifies fragment B of what happened in fragment A using the override onArticleSelected () method.
To ensure that the host activity implements this interface, fragment A's onAttach () method (called by the system when fragment is added to the activity) Forcibly converts the incoming activity type, instantiate an OnArticleSelectedListener object:
public static class FragmentA extends ListFragment { OnArticleSelectedListener mListener; ... @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnArticleSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener"); } } ...}
If the activity does not implement this interface, fragment will throwClassCastExceptionIf the call succeeds, mListener is A reference to the OnArticleSelectedListener interface implemented by activity. Therefore, fragment A can share the event with activity by calling the OnArticleSelectedListener interface.
For example, if fragment A is A subclass of ListFragment, each time you click A list item, the system calls the onListItemClick () method in fragment. In this method, you can call onArticleSelected () method and activity sharing event.
public static class FragmentA extends ListFragment { OnArticleSelectedListener mListener; ... @Override public void onListItemClick(ListView l, View v, int position, long id) { // Append the clicked item's row ID with the content provider Uri Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id); // Send the event and Uri to the host activity mListener.onArticleSelected(noteUri); } ...}Back Stack
The most important difference between activity and fragment lifecycle is how they are stored in their respective back stacks.
When the Activity is stopped, a back stack maintained by the system exists. However, when the fragment is stopped (removed), the programmer must explicitly call addToBackStack (), in addition, fragment exists in a back stack managed by the host activity.
I am the dividing line of tiantiao
Reference: http://www.cnblogs.com/mengdd/archive/2013/01/08/2851368.html
What is android
Android means a robot. android phones use android phones. Google developed android phones and android phones do not know what the android phones mean.
What is android
Android means a robot. android phones use android phones. Google developed android phones and android phones do not know what the android phones mean.