Android UI programming (7) -- Fragment, androidfragment

Source: Internet
Author: User

Android UI programming (7) -- Fragment, androidfragment

Fragment is a part of the Activity interface or an action. You can combine multiple Fragment members into an Activity to create a multi-faceted interface and reuse one Fragment in multiple activities. You can also think of Fragment as a modularized Activity. It has its own life cycle, receives its own events, and can be added or deleted when the Activity is running.

Fragment cannot exist independently. It must be embedded into the activity, and the lifecycle of Fragment is directly affected by the Activity. For example, when an Activity is paused, all its Fragment members are paused. When the Activity is destroyed, all its Fragment members are destroyed. However, when the Activity is running (after onResum (), before onPause (), you can operate each Fragment separately, such as adding or deleting them.When you execute the preceding transaction for Fragment, you can add the transaction to a stack. the stack is managed by the Activity, and each row in the stack is a Fragment transaction. With this stack, You can execute the Fragment transaction in reverse direction, so that you can support the "return" Key (navigation backward) at the Fragment level ).

When adding a Fragment to an Activity, it must be placed in ViewGroup control and define its own Fragment interface. You can declare the Fragment in the layout xml file. The element is <fragment>. You can also create the Fragment in the Code and add it to the ViewGroup control.However, Fragment does not have to be placed on the Activity interface. It can be hidden in the background to work for the Activity.

Fragment highlights:

1. Fragment appears as part of the Activity Interface

2. Multiple Fragment can appear in an Activity at the same time, and one Fragment can also be used in multiple activities.

3. During Activity running, you can add, remove, or replace Fragment (add (), remove (), replace ())

Design Philosophy:

Android introduced Fragment from 3.0 to support more dynamic and flexible interface design, such as applications on tablets. The platform has a larger screen space than the mobile phone to combine and interact with interface components. Fragment makes it unnecessary to cope with complex changes in the View tree when doing such a design. By dividing the layout of an Activity into Fragment, you can change the layout when the Activity is running, and save the change in the back stack of the Activity.

For example, if you write a program to read news, you can use one fragment to display the title list, and the other Fragment to display the content of the selected title. Both Fragment are displayed on one Activity side by side. Both Fragment have their own lifecycles and respond to events of interest. Therefore, you do not need to display the Title List of an Activity like on your mobile phone, and the other Activity displays the news content. Now you can put the two on one Activity and display them at the same time. For example:


Fragment must be written as Reusable Modules. Because Fragment has its own layout, its own event-related, and its own lifecycle and behavior, all of which can contain different instances of one Fragment in multiple activities. This is especially important for the user experience of your interface in different screen sizes. For example, you can start an Activity that contains a lot of Fragment when running the program on a large screen, and start an Activity that contains a few Fragment when running on a small screen.

For example, when the program that read the news just now detects that the program is running on A large screen, it starts activity A and places the Fragment of the Title List and news content in Activity; activity A starts Activity A when it detects that the program is running on A small screen, but there is only the title list Fragment in Activity A. When A title is selected, Activity A starts Activity B, B contains Fragment.

Create Fragment:

To create a Fragment, a new class must be sent from the Fragment or Fragment derived class. Fragment code is written like Activity. It has the same callback method as Activity, such as onCreate (), onStart (), onPause (), and onStop (). In fact, to change the old program to Fragment, you only need to move the code of the Activity callback Method to the corresponding callback method in Fragment.

You usually need to implement the following lifecycle Functions:

OnCreate ()-- This method is called when Fragment is created. You must initialize the basic components of Fragment. For more information, see Activity description.

OnCreateView ()-- This method is called (before display) When Fragment wants to draw its own interface. This method must return the root control of layout of Fragment. If this fragment does not provide an interface, null can be returned. That is, when Fragment draws its user interface for the first time, the system will call this method. To draw the Fragment UI, this method must return a View, which is the root View of the Fragment layout. If Fragment does not provide the UI, null can be returned.

OnPause ()-- When the user is about to leave Fragment, the system calls this method as the first indication (however, it does not always mean that Fragment will be destroyed ). Before the current user painting ends, it is generally necessary to submit any changes that should last long (because the user may not return) here ).

Fragment Lifecycle:


In addition to inheriting the base class Fragment, some subclasses can inherit

DialogFragment

A floating dialog box is displayed. Using this class to create a dialog box is a good choice other than the tool method of the Activity class dialog box, this is because a Fragment dialog box can be merged into the Fragment back stack of Activity management, allowing users to return a previously abandoned Fragment.

ListFragment

Displays a list of projects managed by the Adapter (such as SimpleCursorAdapter), similar to ListActivity. It provides some methods to manage a List View, such as onListItemClick () callback to handle click events.

PreferenceFragment

Displays a list of Preference object hierarchies, similar to PreferenceActivity. This is useful when creating a "set" Activity for the application.

Example 1:

AndroidManifest. xml -- no changes have been made. The default value for creating a project is

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.wxl.fragment"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.wxl.fragment.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>
Fragment1.xml

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: background = "# ffcccc" android: orientation = "vertical"> <TextView android: id = "@ + id/fragment?textview" android: layout_width = "match_parent" android: layout_height = "match_parent" android: gravity = "center" android: text = "first Fragment interface"/> </LinearLayout>
Fragment2.xml

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: background = "# fffccc" android: orientation = "vertical"> <TextView android: id = "@ + id/fragment2_textView" android: layout_width = "match_parent" android: layout_height = "match_parent" android: gravity = "center" android: text = "second Fragment interface"/> </LinearLayout>

Activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal"    tools:context=".MainActivity" >    <fragment         android:id="@+id/fragment1"        android:layout_width="0dip"        android:layout_height="match_parent"        android:name="com.wxl.fragment.Fragment1"        android:layout_weight="1"/>    <fragment         android:id="@+id/fragment2"        android:layout_width="0dip"        android:layout_height="match_parent"        android:name="com.wxl.fragment.Fragment2"        android:layout_weight="1"/></LinearLayout>

Fragment1.java

package com.wxl.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment1 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubreturn inflater.inflate(R.layout.fragment1, container,false);}}
Fragment2.java

package com.wxl.fragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment2 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubreturn inflater.inflate(R.layout.fragment2, container,false);}}
MainActivity. java

package com.wxl.fragment;import android.os.Bundle;import android.support.v4.app.FragmentActivity;public class MainActivity extends FragmentActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }}
Note::

When using Fragment statically in an Activity, pay attention to the following two points:

The packages referenced by Fragment are:Import android. support. v4.app. FragmentInstead of importing android. app. Fragment;

Then the Activity must inherit FragmentActivity.The reference package is: import android. support. v4.app. FragmentActivity;

:


Logcat print information:( FragmentActivity)


Add User Interface:

Fragment is usually used as a part of the user interface of an Activity and provides its layout to the Activity. To provide a layout for a Fragment, the onCreateView () callback method must be implemented. When the Fragment draws its own layout, the Android system calls it. The implementation code of this method must return the Root View of layout of a Fragment.

public class Fragment1 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubreturn inflater.inflate(R.layout.fragment1, container,false);}}
The container parameter passed in onCreateView () is the parent ViewGroup (from layout of Activity) to be inserted by Fragment layout ). The savedInstanceState parameter is a Bundle. If the Fragment is restored, it provides data about the previous Fragment instance.

inflater.inflate(R.layout.fragment1, container,false);

  • Parameter 1: resource ID of the layout to be loaded
  • Parameter 2: parent ViewGroup of the loaded layout. It is very important to pass in the container. The purpose is to allow the system to accept the layout parameter of the Root View to be loaded, which specifies the parent View to be attached.
  • Parameter 3: A boolean value indicates whether the expanded layout should be attached to the ViewGroup during loading (the second parameter ). (In this example, false is specified, because the system has inserted the expanded layout into the container. If it is set to true, an extra ViewGroup is created in the last layout ).
Add Fragment to ActivityGenerally, Fragment provides a part of the UI for the host Activity and is embedded as a whole part of the Activity. There are two ways to add a Fragment to Activity layout.

Method 1: declare fragment in the layout file of the Activity

In this case, you can specify the layout attribute for fragment like a View:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal"    tools:context=".MainActivity" >    <fragment         android:id="@+id/fragment1"        android:layout_width="0dip"        android:layout_height="match_parent"        android:name="com.wxl.fragment.Fragment1"        android:layout_weight="1"/>    <fragment         android:id="@+id/fragment2"        android:layout_width="0dip"        android:layout_height="match_parent"        android:name="com.wxl.fragment.Fragment2"        android:layout_weight="1"/></LinearLayout>
The android: name attribute in <fragment> specifies the Fragment class instantiated in layout.

When the system creates this Activity layout, it instantiates each fragment specified in layout and calls the onCreateView () method on each to obtain the layout of each fragment. The system inserts the returned View directly to the location where the <fragment> element is located.

Note:: Each fragment requires a unique identifier. if the Activity is restarted, the system can restore the fragment (or capture the fragment to process the transaction, for example, remove it)

There are three methods to provide an identifier for a fragment:

  • Provide a unique id for the android: ID attribute
  • Provides a unique string for the android: tag attribute.
  • If none of the above two are provided, the system uses the ID of the container view
Method 2: write code to add fragment to an existing ViewGroup.You can add fragment to Activity layout at any time when the Activity is running. You only need to specify a ViewGroup for fragment to operate fragment transactions (such as adding, removing, or replacing a fragment) in the Activity ), you must use the API from FragmentTransaction to obtain an FragmentTransaction instance from the Activity as follows:
FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Then, you can use the add () method to add a fragment, specifying the fragment to be added and the View to be inserted.
Fragment1 fragment = new Fragment1();  fragmentTransaction.add(R.id.main,fragment);  fragmentTransaction.commit();
The first parameter of add () is the ViewGroup to be put by fragment, which is specified by the resource ID. The second parameter is the fragment to be added. Once a change is made with FragmentTransaction, you must call commit () to make the change take effect (). Fragment1 is the new class for continuing the Fragment base class or derived class.

FragmentManager:

FragmentManager can manage fragment in an Activity and obtain its instance by calling getSupportFragmentManager () of the Activity.

What FragmentManager can do:

1. Use findFragmentById () (used to provide a UI fragment in Activity layout) or findFragmentByTag () (applicable to fragment with or without a UI) to obtain the fragment existing in the Activity.

2. Pop Up fragment from the background stack and use popBackStack () (simulate the user to press the Back command)

3. Use addOnBackStackChangeListenner () to register a Listenner that listens to background stack changes.

FragmentTransaction:

FragmentTransaction: add, remove, replace, and perform other actions on fragment. Get an instance of FragmentTransaction from FragmentManager:

FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Each transaction is a set of changes to be executed at the same time. You can set all the changes you want to execute in a given transaction, such as add (), remove (), replace (), then apply the transaction to the Activity, and you must call commit ().

Example 2-Based on Example 1, some modifications are made to activity_main.xml, Fragment1.java, and MainActivity. java, as shown below:: Fragment1.java Import android. support. v4.app. Fragment from the original export package; this is import android. app. Fragment; Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal"    tools:context=".MainActivity" >        <LinearLayout         android:id="@+id/main_linearLayout1"        android:layout_width="0dip"        android:layout_height="match_parent"        android:layout_weight="1"        android:orientation="vertical">            </LinearLayout>        <LinearLayout         android:id="@+id/main_linearLayout2"        android:layout_width="0dip"        android:layout_height="match_parent"        android:layout_weight="1"        android:orientation="vertical">                <fragment         android:id="@+id/fragment2"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:name="com.wxl.fragment.Fragment2"        />            </LinearLayout></LinearLayout>
MainActivity. java
package com.wxl.fragment;import android.annotation.SuppressLint;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.os.Bundle;import android.support.v4.app.FragmentActivity;public class MainActivity extends FragmentActivity{    @SuppressLint("NewApi") @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);               FragmentManager fragmentManager = getFragmentManager();       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();              Fragment1 fragment1 = new Fragment1();       fragmentTransaction.add(R.id.main_linearLayout1, fragment1);       fragmentTransaction.commit();                  }}
Note:: In this example, fragment2 is directly added in activity_main.xml, while fragment1 is added using code in MainActivity. java. In xml format, android is used when Fragment is added. support. v4.app. fragment; All import packages in Fragment2.java are: import android. support. v4.app. fragment; the code is used, that is, android is used when Fragment is added. app. fragment; All import packages in Fragment1.java are: import android. app. fragment; in this example, we use two methods. java Activity must inherit FragmentActivity (method 1 needs to be used), instead of FragmentActivity. Note::
inflater.inflate(R.layout.fragment1, container,false);
The third parameter must be set to false and cannot be set to true. Otherwise, the following error occurs: The MainActivity. java Activity must inherit FragmentActivity (method 1 needs to be used); otherwise, the following error occurs:

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.