When we need dynamic multi-interface switching, we need to combine UI elements and activity into one module. In 2.3 We usually jump through various activities to achieve multi-interface jumps and a single interface dynamic change. The new features can be used in 4.0 or more systems to easily achieve this effect--fragment class. Fragment is similar to a nested activity that defines its own layout and its own life cycle.
Multiple fragment can be placed in an activity (so it's like a nested activity), and this class can be configured to accommodate different screen sizes (such as tablets and phones).
Here's how you can create a dynamic experience for users through fragment, and also optimize for different screen sizes to give users a better experience. This feature can be run on Android1.6 (of course, Google Library support is required). (all while continuing-to-support devices running versions as old as Android 1.6. This really does not understand, e-text good students pointing out)
Using the Android Library
Android Support Library is a jar file, using this support library allows us to run a high version of the features on the lower version (such as fragment is not a 1.6 feature, but through the introduction of the library, we can run the program containing fragment on 1.6, to ensure program compatibility).
Steps:
1. Download the Android support package via SDK Manager.
2. Create the Libs folder at the top level of the project code and copy the jar library files you need into the libs.
3. Update the manifest file, set as follows
<USES-SDK android:minsdkversion= "4" android:targetsdkversion= "/>"
To ensure that the new API features are not used on the old system, it is necessary to include the following in the file that uses fragment:
Import android.support.v4.app.Fragment;
Import Android.support.v4.app.FragmentManager;
You should declare fragmentactivity (not activity) to contain fragments.
Create fragment
We can think of fragment as a separate activity that has its own life cycle, gets a single trigger event, and can dynamically remove or add fragment while the activity is running. What's even more interesting is that you can reuse the fragment in other places. This section will demonstrate the compatibility of programs by introducing support libraries and inheriting fragment to run programs that contain fragment on a low version (minimum 1.6 version).
Create Fragment class
Just like creating activity classes, inherit fragment, implement some key functions in the life cycle, and remember to put your own functional code inside. To create a fragment, you must define his layout file using Oncreateview (). In fact, this is the only callback function that allows a fragment to run, take a look at the following example:
Import Android.os.Bundle;
Import android.support.v4.app.Fragment;
Import Android.view.LayoutInflater;
Import Android.view.ViewGroup;
public class Articlefragment extends Fragment {
@Override
Bundle savedinstancestate) {
Inflate the layout for this fragment
Return Inflater.inflate (R.layout.article_view, container, false);
}
}
It's a lot easier than the activity, isn't it. Of course, like activity, fragment should also implement functions in other life cycles, so that we can implement the addition and deletion of him. For example, when the activity receives the OnPause () method call, the fragment inside it is also called to OnPause (), so take a good chance and put your code in the OnPause () inside the fragment.
For more detailed fragment please refer here.
Use XML to add fragment to an activity
When reusing fragment, each instantiated fragment must be attached to a parent fragmentactivity, and we can define the fragment in the layout file XML of the parent activity.
Here is an example of adding two fragment to an activity
Res/layout-large/news_articles.xml:
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
android:orientation= "Horizontal"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent" >
<fragment android:name= "Com.example.android.fragments.HeadlinesFragment"
Android:id= "@+id/headlines_fragment"
android:layout_weight= "1"
Android:layout_width= "0DP"
android:layout_height= "Match_parent"/>
<fragment android:name= "Com.example.android.fragments.ArticleFragment"
Android:id= "@+id/article_fragment"
Android:layout_weight= "2"
Android:layout_width= "0DP"
android:layout_height= "Match_parent"/>
</LinearLayout>
See no, in fact, with the general add EditText space does not have any difference, very simple bar.
Tip: to find out how to create a layout that supports more screen sizes, read this article supporting Different screens Sizes.
Here's how to use the code for this layout:
Import Android.os.Bundle;
Import android.support.v4.app.FragmentActivity;
public class Mainactivity extends Fragmentactivity {
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.news_articles);
}
}
Note: By defining fragment in XML, we cannot remove fragment at run time. If we want to have a better interaction with the user by switching fragments, then we need to define fragment when the activity starts.
Create a more flexible UI (advanced application)
When we design applications for a variety of screen-sized devices, we can reuse fragments in different layout files to optimize the customer experience.
For example, on tablets and mobile phones, when using fragment, the performance may be completely different. We can display the front and back of the two fragment on the screen (because the screen space is enough to display, and not let the screen space space), and on the phone two fragment can only switch display, because the phone screen space is too small to display only one screen at a time. The picture is as follows:
We can use class Fragmentmanager to provide a way to add, remove, and overwrite some fragments in the activity at runtime to provide a dynamic and better experience for the customer.
at run time, add a Fragment to the Activity
We already know how to add fragment to the activity's layout file in the section above. Now we'll learn another way, which allows us to dynamically display and hide fragment at runtime. To achieve dynamic management of fragment in the activity, we need to use Fragmentmanager and create fragmenttransaction with it(some columns for fragment operations Api,add /attach/detach/hide, etc.).
If you need to dynamically remove or replace fragments in the activity, we need to add the initialized fragments to the activity in the OnCreate function. One important rule in dealing with fragments, especially when fragments is dynamically added in the run, is that fragment must have a container view to accommodate the layout of the fragments.
The following layout is an alternative to the contents of the previous section, showing only one fragment at a time. In order to replace the current fragment, the layout of the activity must contain a framelayout used as a fragment container.
Note: The layout file file name is the same as the previous section, but the layout folder is not large decorated, so you understand. (It doesn't matter if you don't understand it.) Explanation: Because there is no large modification, so this layout is used on the screen smaller than large, so that the screen can only display one fragment at a time, can not display as a flat two fragment).
res/layout/news_articles.xml:
<framelayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:id= "@+id/fragment_container"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"/>
In your activity, use the Getsupportfragmentmanager () function to get the Fragmentmanager. Use BeginTransaction to create a fragmenttransaction, and call the Add () function for adding a fragment. We can use Fragmenttransaction to perform multiple fragment related operations, and when we are ready to switch, call the function called ().
The following is a fragment added to a layout:
Import Android.os.Bundle;
Import android.support.v4.app.FragmentActivity;
public class Mainactivity extends Fragmentactivity {
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.news_articles);
Check the activity is using the layout version with
The Fragment_container framelayout
if (Findviewbyid (r.id.fragment_container) = null) {
However, if we ' re being restored from a previous state,
Then we don ' t need to do anything and should return or else
We could end up with overlapping fragments.
if (savedinstancestate! = null) {
Return
}
Create an instance of Examplefragment
Headlinesfragment firstfragment = new Headlinesfragment ();
The This activity is started with special instructions from an Intent,
Pass the Intent ' s extras to the fragment as arguments
Firstfragment.setarguments (Getintent (). Getextras ());
Add the fragment to the ' Fragment_container ' framelayout
Getsupportfragmentmanager (). BeginTransaction ()
. Add (R.id.fragment_container, firstfragment). commit ();
}
}
}
Because it is added to the Framelayout container at run time, it is not written to die in XML, so activity can remove and replace the fragment.
how to get in two + Fragment Switch between
The process of replacing fragment with the add difference is good, the difference is that one is replace () function, and the other is the Add () function. It is important to note that when performing a fragment operation, such as replacing or removing a fragment, the user's frequent action is a fallback (backward) or undo operation. To support these actions of the user, we need to call the function Addtobackstack () function before commit () a fragmenttransaction.
Note: When removing or replacing a fragment, and putting this action into the back stack? ), the fragment is stopped (not destroyed) when the fragment is removed. If the user wants to fallback, it takes a fragment from the stack and restarts (restart) it. If you do not join the back stack, the fragment is destroyed directly when it is removed or replaced.
Switch fragment as follows:
Create fragment and give it an argument specifying the article it should show
Articlefragment newfragment = new Articlefragment ();
Bundle args = new bundle ();
Args.putint (Articlefragment.arg_position, POSITION);
Newfragment.setarguments (args);
Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction ();
Replace whatever is in the Fragment_container view with this fragment,
and add the transaction to the back stack so the user can navigate back
Transaction.replace (R.id.fragment_container, newfragment);
Transaction.addtobackstack (NULL);
Commit the transaction
Transaction.commit ();
Addtobackstack () has an optional string parameter that needs to be used when using the APIs of the Fragmentmanager.backstackentry class.
Communication between fragment
In order to reuse the fragment UI, we need to build the fragment into a self-contained (self-closing) system that has its own layout and behavior. Once these reusable fragments are defined, they can be bound to an activity to implement all the active UI. Many times we want to communicate between two fragments (for example, by changing the content based on user input), all fragment communication is through the activity they are attached to, they can never communicate directly with each other.
define an interface
To allow a fragment to communicate with the activity that contains him, we can define an interface in the fragment class and implement it within the activity. Fragment captures the interface implementation inside the Onattach () function, and invokes the interface method and activity communication. (it says that the fragment can only communicate through activity.) )
Take a look at the following examples of fragment and activity communication:
public class Headlinesfragment extends Listfragment {
Onheadlineselectedlistener Mcallback;
Container Activity must implement this interface
Public interface Onheadlineselectedlistener {
public void onarticleselected (int position);
}
@Override
public void Onattach (activity activity) {
Super.onattach (activity);
This makes sure, the container activity has implemented
The callback interface. If not, it throws an exception
try {
Mcallback = (onheadlineselectedlistener) activity;
} catch (ClassCastException e) {
throw new ClassCastException (Activity.tostring ()
+ "must implement Onheadlineselectedlistener");
}
}
...
}
Now fragment can pass the message to the activity through the onarticleselected () function. The purpose of delivery is achieved by using an instance of Onheadlineselectedlistener.
For example, in the following example, when a list element is clicked, a method in the fragment is called. Fragment use Mcallback to instantiate this stuff.
, passing the event to the parent activity to which it is attached.
@Override
public void Onlistitemclick (ListView l, View v, int position, long ID) {
Send the event to the host activity
mcallback.onarticleselected (position);
}
implementing Interfaces
In order to accept event messages from fragment, the parent activity must implement several interfaces defined in the Fragment class. Examples are as follows:
public static class Mainactivity extends Activity
Implements headlinesfragment.onheadlineselectedlistener{
...
public void onarticleselected (int position) {
The user selected the headline of a article from the Headlinesfragment
Do something-to-display that article
}
}
passing messages to Fragment in
The host activity can get the fragment instance through the Findfragmentbyid () function and then pass the message to fragments by accessing the fragments common function.
In the following instance, the host class passes the information obtained in the callback function to another fragment that displays the data:
public static class Mainactivity extends Activity
Implements headlinesfragment.onheadlineselectedlistener{
...
public void onarticleselected (int position) {
The user selected the headline of a article from the Headlinesfragment
Do something-to-display that article
Articlefragment Articlefrag = (articlefragment)
Getsupportfragmentmanager (). Findfragmentbyid (r.id.article_fragment);
if (Articlefrag! = null) {
If article Frag is available, we ' re in Two-pane layout ...
Call a method in the Articlefragment to update its content
Articlefrag.updatearticleview (position);
} else {
Otherwise, we ' re in the One-pane layout and must swap frags ...
Create fragment and give it an argument for the selected article
Articlefragment newfragment = new Articlefragment ();
Bundle args = new bundle ();
Args.putint (Articlefragment.arg_position, POSITION);
Newfragment.setarguments (args);
Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction ();
Replace whatever is in the Fragment_container view with this fragment,
and add the transaction to the back stack so the user can navigate back
Transaction.replace (R.id.fragment_container, newfragment);
Transaction.addtobackstack (NULL);
Commit the transaction
Transaction.commit ();
}
}
}
Android Primary fragment Usage