The Android basics use fragment to adapt to different screens and resolutions (sharing) _android

Source: Internet
Author: User
Tags commit static class unique id

Recently things have been very busy, a new project to rush out, but many functions have to redo, has been writing code, Debug. Today, because a new program to use fragment to do, although the previous use of fragment, but did not study carefully, today by writing an article to record the use of fragment. This article mainly refers to the introduction of the Android website.

Fragment is a new control added after Android3.0, somewhat similar to the activity component, and is also used to host various view elements. Google's addition to the gadget is designed to allow for a partial display of view in a tablet, as long as a view is written so that it can be used on different sizes of devices such as mobile phones and tablets. And this conversion process system helps you get it done. Below we classify to say the use of fragment.

1. Why Use Fragment
Here's an example of an Android website to illustrate the role of fragment: a news application can use a fragment on the left side of the screen to show a list of articles, Then use another fragment on the right side of the screen to show an article--2 a fragment in the same activity, and each fragment has its own set of lifecycle callback methods and handles their own user input events. Thus, instead of using an activity to select an article and another activity to read the article, the user can select an article in the same activity and read it as shown in the picture:

When running on a particularly large screen (for example, a tablet computer), the application can embed 2 fragment in activity A. But if there is not enough space on a normal size screen (such as a cell phone) for 2 fragment, activity A will only contain the fragment of the list of articles, and when the user chooses an article, it starts Activityb, It contains the fragment of reading the article. Therefore, the application can support the 2 design patterns in the above diagram.

Fragment is a component that can be reused for interface views, because fragment defines its own layout, and by defining its own behavior by using its own lifecycle callback method, you can include fragment in multiple activities. This is especially important because it allows you to adapt your user experience to different screen sizes. For example, you might only include multiple fragment in an activity when the screen size is large enough, and, when it does not, start another individual, Use of different fragment activity.

2. Create fragment
To create a Fragment, you must create a Fragment subclass (or inherit from an existing subclass of it). The code for the Fragment class looks like an activity. It contains callback methods similar to the activity, such as OnCreate (), OnStart (), OnPause (), and OnStop (). In fact, if you're going to convert a ready-made Android application to using fragment, you might simply move the code from the callback method of your activity to your fragment callback method.
Let's take a look at the fragment subclasses of the following:

dialogfragment displays a floating dialog box. Using this class to create a dialog box is a good choice to use outside of the dialog tool method of the activity class, because you can combine a fragment dialog box into the fragment back stack of activity management. Allows the user to return to a fragment that had previously been discarded.

listfragment displays a list of items managed by a adapter (such as Simplecursoradapter), similar to listactivity. It provides methods to manage a list view, such as a Onlistitemclick () callback to handle a click event.

preferencefragment displays a list of hierarchies of preference objects, similar to preferenceactivity. This is useful when creating a "set" activity for your application.

3, Fragment life cycle
Below is the fragment lifecycle map, which is excerpted from the Android website.

After inheriting the fragment related class, we need to rewrite several callback functions to implement the relevant functionality, and the following 3 functions are the callback methods that we will generally rewrite:

Copy Code code as follows:

Edited by Mythou
public class Mainfragment extends Fragment
{
Create fragment
public void OnCreate ()
{}

Return to view for activity use
Public View Oncreateview ()
{}

public void OnPause ()
{}

}


OnCreate () The system calls this method when the fragment is created. In the implementation code, you should initialize the necessary components that you want to keep in the fragment, and you can recover when the fragment is paused or stopped.

This method is called by the system when Oncreateview () fragment first draws its user interface. In order to draw the fragment UI, this method must return a view, which is the root view of your fragment layout. If fragment does not provide a UI, you can return null.

When the onpause () User is about to leave fragment, the system calls this method as the first indication (however it does not always mean that the fragment will be destroyed). Before the end of the current user session, you should usually submit any changes that should be persisted here (because the user may not return).
In addition to these, you can see other callback methods in contrast to the life cycle above. We can rewrite the relevant methods as needed.

4. Create fragment
Fragment is often used as part of an activity's user interface and provides its layout to the activity. To provide a layout for a fragment, you must implement the Oncreateview () callback method, which is invoked by the Android system when the fragment draws its own layout. Your implementation code for this method must return a root view of your fragment's layout.

In addition, if your fragment is a listfragment subclass, its default implementation is to return a ListView from Oncreateview (), so it is not generally necessary to implement it.

The view returned from Oncreateview () can also be read and generated from a layout XML resource file. To help you do so, Oncreateview () provides a Layoutinflater object.

Let's take a look at the example of loading view from XML, which dynamically loads the parse XML build view with our general view.

Copy Code code as follows:

Edited by Mythou
public static 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 of the incoming Oncreateview () is your fragmentlayout the parent viewgroup to be inserted (layout from the activity) savedinstancestate parameter is a bundle, If the fragment is restored, it provides data about the previous instance of fragment, and the inflate () method has 3 parameters:

rsid: The resource ID of the layout you want to load.

Container: The parent viewgroup of the loaded layout. Incoming container is important in order to allow the system to accept the layout parameter of the root view of the layout to be loaded, which specifies the parent view to which it is anchored.

• Boolean: Indicates whether the expanded layout should be attached to ViewGroup (the second parameter) during loading (in this case, false because the system has inserted the expanded layout into the container– Pass in true to create an extra view group in the last layout

5, add the fragment to the activity
Typically, fragment provides a part of the UI for host activity that is embedded as part of the entire viewhierarchy of the activity, and there are 2 ways you can add a fragment to the activity layout:

Declare fragment in the layout file of the activity:
In this case, you can specify the layout attribute for fragment as if you were a view. An example is a layout with 2 fragment activity :

Copy Code code as follows:

Edited by Mythou
<?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 property in <fragment> specifies the fragment class that is instantiated in layout. When the system creates this activity layout, it instantiates each of the fragment specified in layout and invokes each Oncreateview () method to obtain fragment for each layout. The system will insert the view returned from fragment directly to the location where the <fragment> element resides. Note: Each fragment requires a unique identity, and if the activity is restarted, the system can be used to recover fragment (and you can also capture fragment to handle transactions, such as removing it).

There are 3 ways to provide an identity for a fragment:
• Provide a unique ID for the Android:id property.
• Provides a unique string for the Android:tag property.
• If none of the above 2 are provided, the system uses the container view ID.

The compose code adds fragment to an existing viewgroup.
Fragment can be added to the activity layout at any time when the activity is running. Simply specify a viewgroup that needs to be placed fragment. To manipulate fragment transactions in your activity (such as adding, removing, or replacing a fragment), you must use APIs from Fragmenttransaction. You can obtain an fragmenttransaction instance from your activity as follows :

Copy Code code as follows:

Fragmentmanager Fragmentmanager =getfragmentmanager ();
Fragmenttransaction fragmenttransaction =fragmentmanager.begintransaction ();

You can then use the Add () method to add a fragment that specifies the fragment to add and the view to insert.
Copy Code code as follows:

fragment = Newexamplefragment ();
Fragmenttransaction.add (r.id.fragment_container,fragment);
Fragmenttransaction.commit ();

The first parameter of add () is the viewgroup that fragment to put in, specified by the resource ID, and the second parameter is the fragment that needs to be added. Once a change has been made with fragmenttransaction, a commit () must be invoked in order for the change to take effect.

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.