This article talks about how to get started using Fragments. dependencies for this post:

  • setting up an Android development environment
  • creating a first application, e.g. hello world
  • using XML files to define layout
  • *using the Support Library (if build target is under API 11)

in order to use Fragments, either your build target have to be API 11 or above, or you have to use the Support Library. my example is given using eclipse as the IDE. this post implements Fragments statically in XML layouts, since it is for the purpose of just 'getting started using Fragments".

  1. create an Android application project (e.g. "HelloFragment_r1").
  2. in the package (e.g. "com.easoncxz.hellofragment_r1"), create a class (e.g. "Frag1", i.e. "com.easoncxz.hellofragment_r1.Frag1", aka the subclass of the Fragment class) that extends the Fragment class, so that a corresponding java file (e.g. "Frag1.java") is created in this package.
  3. in the "res/layout/" folder, create an XML layout (e.g. "frag.xml") for the Fragment - with contents you like.
  4. inflatethis layout in an appropriate method (e.g. "onCreateView") of  class "Frag1":
    • //in the Frag1 class
      public View onCreateView(LayoutInflater myInflater,ViewGroup myContainer,Bundle savedInstanceState){
          myInflater.inflate(R.layout.frag, myContainer,false);
      }
  5. as for the main Activity, load its XML layout file (e.g. main.xml) as usual.
  6. modify "main.xml": add a <fragment> element where you want. this <fragment> element should have an attribute like:
    • android:name="com.easoncxz.hellofragment_r1.Frag1"
  7. done.

reference: