[Android UI design and development] 4. Fragment introduction and simple implementation on the menu bar at the bottom (I), androidfragment

Source: Internet
Author: User

[Android UI design and development] 4. Fragment introduction and simple implementation on the menu bar at the bottom (I), androidfragment

TabActivity has been completely deprecated since Android4.0 and replaced by Fragment. Fragment is a new concept in Android3.0. Fragment is translated into Chinese, which means fragments, but it is very similar to Activity. The following content applies to versions 3.0 and later, and will not be repeated below 3.0.

Official documentation: http://developer.android.com/reference/android/support/v4/app/Fragment.html

1. Introduction to Fragment basic knowledge

1. Fragment features

Android introduced Fragment in Android 3.0 (API level 11.

You can think of Fragment as a module in the Activity. This module has its own layout, lifecycle, and processing of its own input. The Fragment module can be loaded or removed when the Activity is running.

Fragment can be designed as a module that can be reused in multiple activities.

Fragment can be used to achieve flexible layout and improve the user experience when developing applications for both tablet and mobile phones.

2. Fragment Lifecycle

Because Fragment must be embedded in Acitivity, the lifecycle of Fragment is closely related to its Activity.

If the Activity is paused, all Fragment is paused. if the Activity is stopped, all Fragment in the Activity cannot be started. If the Activity is destroyed, all Fragment in it will be destroyed.

However, when the Activity is active, you can independently control the Fragment status, such as adding or removing Fragment.

When performing the fragment transaction (conversion), you can put the fragment intoBack stackSo that the user can perform the return operation.

3. Fragment usage

When using Fragment, You need to inherit the Fragment or Fragment subclass (DialogFragment, ListFragment, PreferenceFragment, WebViewFragment), so the Fragment code looks similar to the Activity.

(1)Use Support Library

The Support Library is a JAR file that provides API Library functions, so that you can use some new versions of APIs on the old Android version.

For example, the full path of the android-support-v4.jar is: <sdk>/extras/android/support/v4/android-support-v4.jar.

  

It provides the Fragment APIs so that Fragment can be used in Android 1.6 (API level 4) and later systems.

To ensure that the new version of APIs is not used on the old version of the system, the following import statement is required:

import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;

At the same time, you should merge the above package into the libs folder under the libs project, and then add in the project Properties: Right-click the project, select Properties, and select Java Build Path on the left, then Add External JARs ..., Add android-support-v4.jar.

  

  When creating an Activity that contains Fragment, if the Support Library is used, the inherited Activity should be FragmentActivity rather than Activity.

 

(2)AverageThree required callback Functions

OnCreate ()

The system calls this method when creating Fragment. The related components should be initialized here, and some items should be retained even when they are paused or stopped.

OnCreateView ()

When the system calls this method when drawing the Fragment UI for the first time, a View must be returned. If Fragment does not provide the UI, null can be returned.

NOTE: If it is inherited from ListFragment, the default Implementation of onCreateView () will return a ListView, so you do not need to implement it yourself.

OnPause ()

When the user leaves Fragment, the first call of this method requires some changes, because the user may not return any more.

 

(3)Implement the Fragment UI

Provides the Fragment UI. The onCreateView () method must be implemented.

If the layout settings of Fragment are written in the frag_list.xml resource file, the onCreateView () method can be written as follows:

Public class FragementList extends Fragment {/*** display the specified view * @ inflater resource ID, specifies the resource file * @ container corresponding to the current Fragment. The parent container control * @ savedInstanceState of the Fragment in the Activity is connected to the layout and its parent container control. In this case, set it to false, because the system has inserted this layout to the parent control, setting it to true will generate a redundant View Group. * // @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater. inflate (R. layout. frag_list, container, false );}}

(4) add Fragment to Activity

When Fragment is added to the Activity, it is in the corresponding View Group.

Fragment has two loading methods: one is to use the label <fragment> declaration in layout of the Activity, and the other is to add it to a specified ViewGroup in the code.

In addition, Fragment can not be any part of the Activity layout. It can be an invisible part.

 

Loading Method 1: Add Fragment to Activity through the layout file of Activity

  In the Activity layout file, add Fragment as a sub-tag.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:baselineAligned="false"    android:orientation="horizontal" >    <fragment        android:id="@+id/frag_list"        android:name="com.yanis.ui.FragementList"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_weight="1" />    <fragment        android:id="@+id/frag_detail"        android:name="com.yanis.ui.FragementDetails"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_weight="2" /></LinearLayout>

The android: name attribute fills in the complete Class name of the created fragment.

  When the system creates a layout file for this Activity, the system will instantiate each fragment and call their onCreateView () method to obtain the layout of the corresponding fragment, insert the returned value to the location where the fragment tag is located.

There are three methods to provide ID for Fragment:

Android: id property: Unique id

Android: tag attribute: unique string

If neither of the above is provided, the system uses the container view ID.

    

Loading Method 2: Add Fragment to a ViewGroup by programming

When the Activity is in the Running state, you can dynamically add Fragment to the layout of the Activity. You only need to specify the parent View Group to add the Fragment.

First, you need a FragmentTransaction instance:

FragmentManager fragmentManager = getFragmentManager()FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

 (Note: If you import android. support. v4.app. FragmentManager;The Support Library is used,In this case, FragmentManager fragmentManager = getSupportFragmentManager ();)

Then, use the add () method to add the Fragment object:

ExampleFragment fragment = new ExampleFragment();fragmentTransaction.add(R.id.fragment_container, fragment);fragmentTransaction.commit();

The first parameter is the container of the fragment, that is, the parent control group.

Finally, you need to call the commit () method to make the change of the FragmentTransaction instance take effect.

 

4. Have a simple Chestnut

 

Method 1:Add Fragment to Activity through Activity layout File

As follows:

  

The layout file is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:baselineAligned="false"    android:orientation="horizontal" >    <fragment        android:id="@+id/frag_list"        android:name="com.yanis.ui.FragementList"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_weight="1" />    <fragment        android:id="@+id/frag_detail"        android:name="com.yanis.ui.FragementDetails"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_weight="2" /></LinearLayout>

 

Method 2: Add Fragment to a ViewGroup by programming

As follows:

  

1. The homepage layout file is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:baselineAligned="false"    android:orientation="horizontal" >    <LinearLayout        android:id="@+id/frag_list"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_weight="1" android:orientation="vertical">        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="List" />    </LinearLayout>    <LinearLayout        android:id="@+id/frag_detail" android:orientation="vertical"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_weight="2" >        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="Details" />    </LinearLayout></LinearLayout>

2. the Activity code is as follows:

package com.yanis.ui;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;public class MainActivity extends FragmentActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //setContentView(R.layout.activity_main);        setContentView(R.layout.activity_maino);        FragmentManager fragmentManager = getSupportFragmentManager();        FragmentTransaction fragmentTransaction = fragmentManager                .beginTransaction();        FragementList fragment1 = new FragementList();        fragmentTransaction.add(R.id.frag_list, fragment1);        FragementDetails fragment2 = new FragementDetails();        fragmentTransaction.add(R.id.frag_detail, fragment2);        fragmentTransaction.commit();    }}

 

Source code: https://github.com/YeXiaoChao/Yc_ui_fragment

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.