Android class reference --- Fragment (1)

Source: Internet
Author: User

1. inheritance relationship

Java. lang. Object

|__ Android. app. Fragment

Implementation interface: ComponentCallbacks2 View. OnCreateContextMenuListener

Introduced version: API Level 11

Subclass:

DialogFragment, ListFragment, PreferenceFragment, WebViewFragment

2. class overview

A Fragment is a Fragment of the application's user interface or behavior. It can be placed in an Activity. The FragmentManager object is used to interact with the Fragment object. The FragmentManager object can be obtained through the Activity. getFragmentManager () method and Fragment. getFragmentManager () method.

Fragment class is widely used. Its core is to represent a special operation or interface running in a large Activity. Fragment objects are closely related to the Activity objects they are attached to and cannot be used separately. Although Fragment objects define their own lifecycles, this lifecycle depends on the Activity in which it is located: if the Activity is terminated, its internal Fragment cannot be started; when an Activity is destroyed, all its Fragment objects are destroyed.

All Fragment subclasses must contain a public empty constructor. When necessary, the Framework will often re-instantiate the Fragment class. During special State recovery, you need to find this constructor to instantiate the Fragment class. If the empty constructor is invalid, an exception occurs during recovery.

Older platforms

Although the Fragment API was introduced in the HONEYCOMB version, FragmentActivity can also be used on older platforms.

Claim period

Although the lifecycle of a Fragment object depends on its Activity object, it also has its own standard Activity cycle. It contains basic Activity cycle methods, such as onResume (), but it also contains important methods related to Activity and UI interaction.

The core lifecycle method to be called when displaying Fragment (interacting with users) is as follows:

1. Call the onAttach (Activity) method when associating the Fragment object with the Activity;

2. Call the onCreate (Bundle) method when the Fragment object is initially created;

3. The onCreateView (LayoutInflater, ViewGroup, Bundle) method is used to create and return View objects associated with Fragment;

4. The onActivityCreate (Bundle) method tells the Fragment object that the Activity object it attaches has completed the execution of the Activity. onCreate () method;

5. The onStart () method will display the Fragment object to the user (after the Activity containing the Fragment object is started );

6. onResume () will allow the Fragment object to interact with the user (after the Activity containing the Fragment object is started and restored ).

The method for reverse callback when the Fragment object is no longer used:

1. because the Activity object attached to the Fragment object is suspended, or an action to modify the Fragment object is being executed in the Activity, the Fragment object will no longer interact with the user, the system calls the onPause () method of the Fragment object;

2. because the Activity object attached to the Fragment object is terminated, or an operation to modify the Fragment object is being executed in the Activity, the Fragment object is no longer displayed to the user, the system calls the onStop () method of the Fragment object.

3. The onDestroyView () method is used to clear resources associated with the View object in Fragment;

4. Call the onDestroy () method after the final state of the Fragment object is cleared;

5. When the Fragment object is no longer associated with the Activity it is attached to, the onDetach () method will be called immediately.

 

Layout

Fragment objects can be used for the layout of applications. It makes the code more modular and makes it easier to adjust the user interface for the screens running Fragment. For example, a simple program consists of a project list and project details.

The layout XML of an Activity can contain the <Fragment> label of the fragment instance to be embedded in the layout. For example, in the following example, a Fragment object is embedded in the layout:

<FrameLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "match_parent" android: layout_height = "match_parent">
<Fragment class = "com. example. android. apis. app. FragmentLayout $ TitlesFragment"
Android: id = "@ + id/titles"
Android: layout_width = "match_parent" android: layout_height = "match_parent"/>
</FrameLayout>

The following is a common method for installing a layout in an Activity:

@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );

SetContentView (R. layout. fragment_layout );
}

Depending on the ListFragment object, it is quite simple to display the title of the list. Note that clicking the implementation of a list item will depend on the layout of the current Activity. It can create a new Fragment to display details of the project, you can also start a new Activity to display project details.

Public static class TitlesFragment extends ListFragment {
Boolean mDualPane;
Int mCurCheckPosition = 0;

@ Override
Public void onActivityCreated (Bundle savedInstanceState ){
Super. onActivityCreated (savedInstanceState );

// Populate list with our static array of titles.
SetListAdapter (new ArrayAdapter <String> (getActivity (),
Android. R. layout. simple_list_item_activated_1, Shakespeare. TITLES ));

// Check to see if we have a frame in which to embed the details
// Fragment directly in the containing UI.
View detailsFrame = getActivity (). findViewById (R. id. details );
MDualPane = detailsFrame! = Null & detailsFrame. getVisibility () = View. VISIBLE;

If (savedInstanceState! = Null ){
// Restore last state for checked position.
MCurCheckPosition = savedInstanceState. getInt ("curChoice", 0 );
}

If (mDualPane ){
// In dual-pane mode, the list view highlights the selected item.
GetListView (). setChoiceMode (ListView. CHOICE_MODE_SINGLE );
// Make sure our UI is in the correct state.
ShowDetails (mCurCheckPosition );
}
}

@ Override
Public void onSaveInstanceState (Bundle outState ){
Super. onSaveInstanceState (outState );
OutState. putInt ("curChoice", mCurCheckPosition );
}

@ Override
Public void onListItemClick (ListView l, View v, int position, long id ){
ShowDetails (position );
}

/**
* Helper function to show the details of a selected item, either
* Displaying a fragment in-place in the current UI, or starting
* Whole new activity in which it is displayed.
*/
Void showDetails (int index ){
MCurCheckPosition = index;

If (mDualPane ){
// We can display everything in-place with fragments, so update
// The list to highlight the selected item and show the data.
GetListView (). setItemChecked (index, true );

// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
GetFragmentManager (). findFragmentById (R. id. details );
If (details = null | details. getShownIndex ()! = Index ){
// Make new fragment to show this selection.
Details = DetailsFragment. newInstance (index );

// Execute a transaction, replacing any existing fragment
// With this one inside the frame.
FragmentTransaction ft = getFragmentManager (). beginTransaction ();
Ft. replace (R. id. details, details );
Ft. setTransition (FragmentTransaction. TRANSIT_FRAGMENT_FADE );
Ft. commit ();
}

} Else {
// Otherwise we need to launch a new activity to display
// The dialog fragment with selected text.
Intent intent = new Intent ();
Intent. setClass (getActivity (), DetailsActivity. class );
Intent. putExtra ("index", index );
StartActivity (intent );
}
}
}

The detailed Fragment object only displays the detailed text string of the selected object, which is obtained based on the index of a character array built in the application:

Public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized
* Show the text at 'index '.
*/
Public static DetailsFragment newInstance (int index ){
DetailsFragment f = new DetailsFragment ();

// Supply index input as an argument.
Bundle args = new Bundle ();
Args. putInt ("index", index );
F. setArguments (args );

Return f;
}

Public int getShownIndex (){
Return getArguments (). getInt ("index", 0 );
}

@ Override
Public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState ){
If (container = null ){
// We have different layouts, and in one of them this
// Fragment's containing frame doesn't exist. The fragment
// May still be created from its saved state, but there is
// No reason to try to create its view hierarchy because it
// Won't be displayed. Note this is not needed -- we cocould
// Just run the code below, where we wocould create and return
// The view hierarchy; it wocould just never be used.
Return null;
}

ScrollView scroller = new ScrollView (getActivity ());
TextView text = new TextView (getActivity ());
Int padding = (int) TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_DIP,
4. getActivity (). getResources (). getDisplayMetrics ());
Text. setPadding (padding, padding );
Scroller. addView (text );
Text. setText (Shakespeare. DIALOGUE [getShownIndex ()]);
Return scroller;
}
}

When a user clicks the title, there is no detail container in the current Activity. Therefore, the Click Event code of the title Fragment starts a new Activity that displays the details of Fragment:

Public static class DetailsActivity extends Activity {

@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );

If (getResources (). getConfiguration (). orientation
= Configuration. ORIENTATION_LANDSCAPE ){
// If the screen is now in landscape mode, we can show
// Dialog in-line with the list so we don't need this activity.
Finish ();
Return;
}

If (savedInstanceState = null ){
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment ();
Details. setArguments (getIntent (). getExtras ());
GetFragmentManager (). beginTransaction (). add (android. R. id. content, details). commit ();
}
}
}

However, the screen may show enough details about the Title List and the selected title. For a layout like this on a horizontal screen, it can be placed under layout-land:

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "horizontal"
Android: layout_width = "match_parent" android: layout_height = "match_parent">

<Fragment class = "com. example. android. apis. app. FragmentLayout $ 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 "/>

</LinearLayout>

Note that the preceding Code adjusts this optional UI stream: The title Fragment object is embedded into the detailed Fragment object within the Activity, if the Fragment object runs in a configuration environment with a display space, the detailed Activity will be completed by itself.

When the Fragment objects held by the Activity are restarted due to configuration changes, their new Fragment instances can use different la s than the previous la S. In this case, all the previous Fragment objects will still be instantiated and run in the new instance. However, any View object not associated with <fragment> will not be created again, and false will be returned in the re-isInLayout () method.

When the View object of Fragment is bound to the parent container, the attributes of the <fragment> label are used to control the information provided to the LayoutParams object. They can be used as the onInflate (Activity, attributeSet, Bundle) method parameters for parsing.

The instantiated Fragment object must have a unique identifier of some types, so that its parent Activity can be re-associated to the previous instance when it is destroyed and rebuilt. You can use the following methods to implement this association:

1. If it is not explicitly specified, the View ID of the container is used for identification;

2. Use the android: tag attribute of the <fragment> element to provide a specific tag name for the Fragment object element;

3. Use the android: id attribute of the <fragment> element to provide a specific identifier for the element of the Fragment object.

 


From FireOfStar's column

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.