Android learning Route 21: Use Fragment to build a dynamic UI -- create a Fragment
You can regard fragment as a modular part of an activity. It has its own lifecycle and accepts its own input events, you can add or delete an activity when it is running (like a "sub-activity", you can reuse it in different activities ). This lesson will show you how to use Support Libaray inheritanceFragmentClass to make your application compatible with devices running Android 1.6.
Tip:If you decide that the minimum API level for your application is 11 or higher, you do not need to use the Support Library. You can directly use the APIs related to the platform that contains the Fragment class. The main focus of this lesson is to use the APIs of the Support Library, which is different from the platform version that already contains the Fragment class by using a specified package signature and slightly different API names.
Before you begin this course, you must set up your project to use the Support Library. If you have not used the Support Library before, follow the Support Library Setup document to set your project usageV4Library. You can also useV7 appcompatLibrary allows your app activity to use action bar, which is compatible with Android 2.1 (API level 7) and also containsFragmentAPIs.
Create a Fragment
To create a Fragment, first inheritFragmentClass, and then overwrite the main lifecycle method to insert your application logic, similarActivityClass.
CreateFragmentThe difference with activity is that you must useonCreateView()Callback method to define the layout. In fact, you only need to override this callback method to make this fragment work. The following is an example of a simple fragment layout:
import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.ViewGroup;public class ArticleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.article_view, container, false); }}
Like an activity, fragment needs to implement other callback methods to allow you to manage its status when it is added or removed in actvity, it is like its lifecycle status during activity switching. For exampleonPause()Method is called, and all fragment within it will receiveonPause()Method callback.