Android 4 Learning (8): User interface-Fragment

Source: Internet
Author: User
Tags visibility

Refer to "Professional Android 4 Development"

Fragment Introduction

Fragment is that we can separate the activity into components that have their own lifecycle and UI. Its greatest use is to fit different screens. Create fragment

There are many similarities between fragment and activity, for example, without the UI, but it doesn't seem to make much sense for both. They are also created in similar ways, such as the following code:

Package test.fragments;
Import android.app.Fragment;
Import Android.os.Bundle;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
public class Myskeletonfragment extends Fragment {
@Override public
View Oncreateview (Layoutinflater inflater,  
viewgroup Container,
Bundle savedinstancestate) {
//Create, or inflate the Fragment ' s UI, and return it.
If This Fragment has the no UI then return null.
Return Inflater.inflate (R.layout.my_fragment, container, false);
}
}
Fragment life cycle

The fragment life cycle is closely related to its host activity, almost consistent with the life cycle of the host activity, and the biggest difference is that activity can add to or remove fragment. The following figure summarizes the lifecycle of the fragment:

fragment-specific life cycle events

Attach and Detach Fragment from the parent activity creating and destroying Fragment creating and destroying UI

Get fragment Manager

Each activity object has a Fragmentmanager object built into it, using Getfragmentmanager () to obtain:

Fragmentmanager Fragmentmanager = Getfragmentmanager (); add fragment to activity

The easiest way to add fragment to an activity is to use a layout configuration file, such as:

<?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.paad.weatherstation.MyListFragment"
android:id  = "@+id/my_list_fragment"
android:layout_width= "match_parent"
android:layout_height= "Match_parent"
android:layout_weight= "1"
/>
<fragment android:name= "Com.paad.weatherstation.DetailsFragment"
android:id= "@+id/details_fragment"
android:layout_width= "match_parent"
android:layout_height= " Match_parent "
android:layout_weight=" 3 "
/>
</LinearLayout>

After invoking the inflate method to generate the fragment interface, fragment is actually a viewgroup-like role that manages its own UI in the activity.

The above method of adding fragment to an activity lacks flexibility and cannot be dynamically added and deleted, preferably using fragmenttranaction and configuration files like the following:

<?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" >
<framelayout
android:id= "@+id/ui_container"
Match_parent "
android:layout_height=" match_parent "
android:layout_weight=" 1 "
/>
< Framelayout
android:id= "@+id/details_container"
android:layout_width= "Match_parent"
android: layout_height= "Match_parent"
android:layout_weight= "3"
/>
</LinearLayout>
using Fragmenttransaction

Fragmenttransaction can add, remove, or replace fragment at run time, enabling dynamic UI changes. The Fragment transaction is created by the BeginTransaction () method of Fragment manager, which can then be added, deleted, and replaced by Fragment, and then submitted for modification by the commit () method.

Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
ADD, remove, and/or replace fragments.
Specify animations.
Add to back stack if required.
Fragmenttransaction.commit ();
Add, remove, and replace fragment

The main argument for adding a new Fragment,add () method using the Fragmenttransaction Add method is fragment container view (or its ID) and fragment instance, for example:

Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
Fragmenttransaction.add (R.id.ui_container, New Mylistfragment ());
Fragmenttransaction.commit ();

Removing fragment requires the fragmenttransaction remove () method, which is fragment object, and fragment object can be obtained by Fragmentmanager () method.

Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
Fragment Fragment = Fragmentmanager.findfragmentbyid (r.id.details_fragment);
Fragmenttransaction.remove (fragment);
Fragmenttransaction.commit ();

Replacement fragment uses the Fragmenttransaction replace () method, which is the ID of the container in which the fragment is substituted, and the new fragment:

Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
Fragmenttransaction.replace (R.id.details_fragment, New Detailfragment (Selected_index));
Fragmenttransaction.commit ();
gets the specified fragment

There are two ways to get a particular fragment, and if the fragment has been added to a layout file, you can use the ID in the XML file as an argument:

Myfragment myfragment = (myfragment) Fragmentmanager.findfragmentbyid (r.id.myfragment);

You can also get a specific fragment by adding tag when you create a fragment:

Myfragment myfragment = (myfragment) fragmentmanager.findfragmentbytag (My_fragment_tag);
Delete Fragment container

You can delete a fragment by setting the visibility property to "Gone" in the configuration file, for example:

<?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" >
<framelayout
android:id= "@+id/ui_container"
Match_parent "
android:layout_height=" match_parent "
android:layout_weight=" 1 "
/>
< Framelayout
android:id= "@+id/details_container"
android:layout_width= "Match_parent"
android: layout_height= "Match_parent"
android:layout_weight= "3"
android:visibility= "Gone"
/>
</LinearLayout>
fragment and back Stack

The activity has an activity Stack that returns to the previous activity when the user presses the "Back" button. Fragment can also respond to the "return" event by Fragmenttransaction invoking the Addtobackstack () method before a commit. This way, after the user presses the return key, Android will first reproduce the previous UI layout.

Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
Fragmenttransaction.add (R.id.ui_container, New Mylistfragment ());
Fragment Fragment = Fragmentmanager.findfragmentbyid (r.id.details_fragment);
Fragmenttransaction.remove (fragment);
String tag = null;
Fragmenttransaction.addtobackstack (tag);
Fragmenttransaction.commit ();

The principle is similar to activity, and after invoking Addtobackstack (), the fragment is pushed into the back stack instead of being destroyed. animation effect of Fragment transaction

There are two ways to animate Fragment transaction, respectively:

Set Gradual: Transaction.settransition (Fragmenttransaction.transit_fragment_open);

To set the animation effect:

Fragmenttransaction.setcustomanimations (R.animator.slide_in_left, r.animator.slide_out_right);

interface between fragment and host activity

Fragment can obtain host activity objects through the Getactivity () method:

TextView TextView = (TextView) getactivity (). Findviewbyid (R.id.textview);

Another common way of interacting between fragment and activity is to use a callback function:

Public interface Onseasonselectedlistener {public
void onseasonselected (Season Season);
}
Private Onseasonselectedlistener Onseasonselectedlistener;
Private Season Currentseason;
@Override public
void Onattach [activity activity] {
Super.onattach (activity);
try {
Onseasonselectedlistener = (onseasonselectedlistener) activity;
catch (ClassCastException e) {
throw new ClassCastException (activity.tostring () + "must implement ONSEASONSELECTE  Dlistener ");
}
private void Setseason (Season Season) {
Currentseason = Season;
Onseasonselectedlistener.onseasonselected (season);
}
fragment with no UIAlthough uncommon, fragment does have no UI, and the benefit may be more flexible lifecycle control. There are no UI fragment lifecycle events:
public class Newitemfragment extends Fragment {
@Override public
void Onattach (activity activity) {	s Uper.onattach (activity);	Get a Type-safe reference of the parent activity.
@Override public
    void OnCreate (Bundle savedinstancestate) {
	super.oncreate (savedinstancestate);
	Create background worker threads and tasks.
@Override public
void onactivitycreated (Bundle savedinstancestate) {
	super.onactivitycreated (  Savedinstancestate);
	Initiate worker threads and tasks.
}
}   
Common Fragment ClassDiagfragment listfragment webviewfragment

















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.