A Fragment is basically a sub-activity. It’s a mini-activity but has it’s own lifecycle. However Fragments cannot exist on their own and have to be hosted by an activity.In this tutorial we will look at the Fragment class in a practical manner. We will examine several examples to explaun concepts.

 

Quick Android Fragment Examples and HowTo’s

1. How to Replace a Fragment Using FragmentTransaction

Yeah, we can easily replace a fragment via FragmentTransaction.

But first we need a placeholder where the Fragment will be inserted within our activity.

So for example if you have a layout like activity_main.xml, then within that layout add a placeholder like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 
    
    android_id="@+id/drawer_layout"
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_clickable="true">
        ......
        <FrameLayout
            android_id="@+id/main_frame"
            android_layout_weight="1"
            android_layout_width="match_parent"
            android_layout_height="0dp">
            .....
</android.support.v4.widget.DrawerLayout>

So in our case we’ve used the framelayout, however you can use any layout.

All we need is a place where our Fragment will be rendered and FrameLayout is perfect for that.

Then we proceed to our java code.

Let’s create a method that will receive a Fragment object as a parameter.

We’ll then start by retrieving the FragmentManager using the getSupportFragmentManager() method of the activity.

Then calling the beginTransaction() of that FragmentManager will give us a FragmentTransaction instance.

Then we can use that FragmentTransaction to replace the FrameLayout we defined above with our Fragment using the replace() method.

Then we make sure we commit that Transaction.

    private void replaceFragmentAnimation(Fragment fragment) {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.main_frame, fragment);
        transaction.commit();

    }
2. How to Replace a Fragment with Animation Transitions

You may want to show animations, or page transitions as you replace or navigate to Fragments. Normally FragmentTransaction class is what allows us replace Fragments and we’ve seen how to do that.

Now let’s see how to use animations as we transit to a Fragment.

First we need to define an animation resource file. In your res directory add another directory called anim.

Then create the following xml animation files in that anim directory;

slide_left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<!--Slide from left to right-->
<set 
    android_fillAfter="true">

    <translate
        android_duration="200"
        android_fromXDelta="-100%p"
        android_toXDelta="0"/>
</set>

slide_left_out.xml


<?xml version="1.0" encoding="utf-8"?>
<!--Slide out from right to left-->
<set >
    <translate
        android_duration="200"
        android_fromXDelta="0"
        android_toXDelta="-100%p"/>
</set>

slide_right_in.xml

<?xml version="1.0" encoding="utf-8"?>
<!--Slide from right to left-->
<set 
    android_fillAfter="true">

    <translate
        android_duration="200"
        android_fromXDelta="100%p"
        android_toXDelta="0"/>
</set>

slide_right_out.xml

<?xml version="1.0" encoding="utf-8"?>
<!--Slide out from left to right-->
<set >
    <translate
        android_duration="200"
        android_fromXDelta="0"
        android_toXDelta="100%p"/>
</set>

Then inside your activity as class fields have the following constants:

 Private final int SLIDE_FROM_LEFT_TO_RIGHT = 0 ; //Sliding the page from left to right 
 private final int SLIDE_FROM_RIGHT_TO_LEFT = 1 ; // Swing the page's animation from right to left   

Then within a method inside your activity:

    private void replaceFragment(Fragment fragment, int slideType) {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        switch (slideType){
            case SLIDE_FROM_LEFT_TO_RIGHT:
                transaction.setCustomAnimations(R.anim.slide_left_in,R.anim.slide_right_out);
                break;
            case SLIDE_FROM_RIGHT_TO_LEFT:
                transaction.setCustomAnimations(R.anim.slide_right_in,R.anim.slide_left_out);
                break;
        }

        transaction.replace(R.id.main_frame, fragment);
        transaction.commit();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //maybe activate some buttons or something else
            }
        }, 200);
    }

You can see this time our method has received a Fragment as well as an integer to identify the type of sliding animation we want to make.

Then you can use that method like this:

    replaceFragment(orderFragment, SLIDE_FROM_LEFT_TO_RIGHT);

Android FragmentTransaction Introduction

When you mention the term transaction the first thing that probably comes to mind is finance. Making financial transactions in your bank or something like that.

The noun transaction_ comes from the verb transact. The verb transact was based on the Latin language term transigere which is dated 1500-1600 and means to drive throgh or to carry to completion or to finish according to Merriam-Webster’s Collegiate Dictionary.

However that term is not limited to business or financial transaction only.

We can also transact fragments, or do a Fragment Transaction instead of a Business Transaction. And this basically means carrying a set of operations on Fragments.

Android Framework provides us with a set of APIs that allow us to complete these Fragment Transactions.

These APIs are encapuslated in a class called FragmentTransaction. FragmentTransaction was added in API level 1 of android. That class is class. This basically means that it provides generalizations to it’s subclasses and is not exactly a concrete class itself.

===

Variations of FragmentTransaction class.

Android as a Framework loves to support older devices hence it provides variations of various APIs common known as support libraries that can provide compatibility with those devices as old as methuselah.

FragmentTransaction is no exception and provides with :

  1. android.app.FragmentTransaction
  2. android.support.v4.app.FragmentTransaction – supports platforms prior to Android 3.0.

FragmentTransaction Programmatic Definition

Let’s now see it’s programmatic definition using code as opposed to words.

First it’s a class. A class is blueprint for creation of objects:

..class FragmentTransaction..{..}

As a class it resides in a package like all other classes in java.

package android.app;

The above is the FragmentTransaction defined in the Framework.
However there is also the second variation defined in the support framework to target devices prior to Android 3.0:

package android.support.v4.app;

It’s a public class meaning that it’s visible to classes within it’s or other packages:

public class FragmentTransaction..{}

However it’s also an abstract class:

public abstract class FragmentTransaction ..{}

Lastly it derives from java.lang.Object like all other classes in java.

public abstract class FragmentTransaction extends Object {}

 

Android FragmentTransactions – Show Dynamic Fragments With ListViews

 

In this simple example here,we shall be seeing how to perform a fragment transaction on dynamic fragments.

By dynamic we mean that our Fragments get created programmatically at runtime as opposed to using XML Layouts.

We shall simply replace our layout with two fragments,each with its own layout and with simple ListViews.Take note our fragments are created dynamically on code,then we replace them and commit the transaction.

 

Section 1 : Fragment One Class

  • Contains a simple listview in its layout.
package com.tutorials.dynamicfragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Fragment1 extends Fragment{

  ListView lv;
  ArrayAdapter<String> adapter;
  String[] names={"Daley Blind","Chrid Smalling","Matteo Darmian","Luke Shaw"};

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {

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

    lv=(ListView) rootView.findViewById(R.id.listView1);
    adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,names);
        lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> arg0, View v, int pos,
          long id) {
        // TODO Auto-generated method stub

        Toast.makeText(getActivity(), names[pos], Toast.LENGTH_SHORT).show();
      }
    });

    return rootView;
  }

}

Section 2 : Fragment Two Class

  • Contains a simple listview in its layout.
package com.tutorials.dynamicfragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Fragment2 extends Fragment{

ListView lv;
ArrayAdapter<String> adapter;
    String[] positions={"Midfielder","Defender","FullBack","Forward","Mid","Winger","FullBack","Winger","CenterBack"};

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {

    View rootView=inflater.inflate(R.layout.fragment2, container,false);

    lv=(ListView) rootView.findViewById(R.id.listView1);
    adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,positions);

    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
          long id) {
        // TODO Auto-generated method stub
        Toast.makeText(getActivity(), positions[pos], Toast.LENGTH_SHORT).show();
      }
    });

    return rootView;
  }

}

Section 3 : MainActivity Class

  • We perform and commit Fragment Transactions.
package com.tutorials.dynamicfragments;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //WE NEED FRAGMENT MANAGER ASSOCIATED WITH THIS ACTIVITY
        FragmentManager fm=getFragmentManager();

        //LETS START FRAGMENT TRANSACTION
        FragmentTransaction ft=fm.beginTransaction();

        //INSTANTIATE OUR TWO FRAGEMNTS
        Fragment f1=new Fragment1();
        Fragment f2=new Fragment2();

        //LETS REPLACE FISRT OUR MAIN LAYOUT THEN THE LINEAR LAYOUT INSIDE IT WITH OUR RESPECTIVE FRAGMENTS
        ft.replace(android.R.id.content, f1);
        ft.replace(R.id.content2, f2);

        //IT WAS A TRANSACTION SO WE COMMIT IT
       ft.commit();

    }

}

Section 4 : Layouts

(a). ActivityMain.xml
  • Contains layouts we shall be replacing.
<RelativeLayout 
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_background="#009968"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    tools_context=".MainActivity" >

    <LinearLayout
        android_id="@+id/content2"
        android_layout_width="match_parent"
        android_layout_height="350dp"
        android_layout_alignParentBottom="true"
        android_layout_marginBottom="22dp"
        android_background="#2fc1b9"
        android_orientation="vertical" >
    </LinearLayout>

</RelativeLayout>
(b). Fragment1 Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_orientation="vertical" >

    <ListView
        android_id="@+id/listView1"
        android_layout_width="match_parent"
        android_layout_height="wrap_content" >
    </ListView>

</LinearLayout>
(c). Fragment 2 Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_orientation="vertical" >

    <ListView
        android_id="@+id/listView1"
        android_layout_width="match_parent"
        android_layout_height="wrap_content" >
    </ListView>

</LinearLayout>

 

Android ActionBar SwipeTabs ViewPager – Fragments With GridViews

It’s important that we know how to construct applications that can be swiped. Alot of the times while interacting with apps you see the ability to swipe being integrated in modern applications.

This ability in android is enable by a class called android.support.v4.View.ViewPager.

ViewPager gives us this ability to swipe.

Moreover we may want our users to have the ability to click through the tabs and navigate appropriately the application. Users probably intuitively expect this.

So we make use of ActionBar Tabs. Tabs allow us to navigate pages/fragments by clicking them.

Here are the advantages of Tabs:

What the App does

In this case our application will comprise three tabs.

Each Tab will display a Fragment and each Fragment will contain a gridview.

Each GridView will have it’s own data. These data can be from any source but for simplicity sake we use a String array as our data source.

Each String array will contain a list of countries from Asian, African and European continents.

Our tab are actionbar tabs.

What is ActionBar

An actionbar is a primary toolbar normally appearing at the top of the activity’s window.

Here are the main functions of an actionbar:

  1. Display the activity title.
  2. Allow for navigation throughout the whole application.
  3. Provide a consistent theming throughout the application irrespective of the activity.

Our Swipeable Fragments

We'll have three fragments that our users will be able to swipe through. The swiping functionality is enabled by the ViewPager class.

1. Asia Fragment

This is our Asia Fragment. It represents the Asian continent and it will containa gridview.

This GridView will display some of the countries within the asian continent.

We are going to hold these countries in a string array. So basically that array is our data source.

Here are the functions of this fragment:

Here's our source code.

    package com.tutorials.viewpagertabsgridview;

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.GridView;

    public class Asia extends Fragment {

       String[] countries={"India","Pakistan","Malaysia","Bangladesh","Singapore","China","Syria","Saudi Arabia"};
       ArrayAdapter<String> adapter;
       GridView gv;

       @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         View rootView=inflater.inflate(R.layout.asia, null);

         gv=(GridView) rootView.findViewById(R.id.gridView1);

         adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,countries);

         gv.setAdapter(adapter);

        return rootView;
      }

    }

2. Africa Fragment

This is our Africa Fragment. This Fragment will contain a Gridview that will contain our African counrtries.

As a class this fragment will derive from android.support.v4.app.Fragment making it a Fragment.

Here are the functions of this fragment:

Here's the code:

    package com.tutorials.viewpagertabsgridview;

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.GridView;

    public class Africa extends Fragment {

      String[] countries={"Kenya","Nigeria","Rwanda","South Africa","Egypt","Uganda","Zambia","Libya"};
       ArrayAdapter<String> adapter;
       GridView gv;

       @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         View rootView=inflater.inflate(R.layout.africa, null);

         gv=(GridView) rootView.findViewById(R.id.gridView1);

         adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,countries);

         gv.setAdapter(adapter);

        return rootView;
      }

    }

3. Europe Fragment

This is our Europe Fragment. This European Fragment will contain a GridVoew that will hold our European countries.

That GridView will be bound to a string array as our data source. Normally these data binding requires an adapter so we will use an arrayadapter which is a child of BaseAdapter.

This European Fragment will derive from android.support.v4.app.Fragment making it a Fragment.

Here are the functions of this european fragment:

No. Responsibility
1. Hold a String array containing European countries. This String array will be our data source.
2. Define an ArrayAdapter to adapt those countries to an adapterview.
3. Define a GridView to hold our European countries. A GridView is an adapterview that holds data in a two dimensional format.
4. Override the onCreateView() method of the android.support.v4.app.Fragment class.
5. Inflate the R.layout.europe layout into our Fragment and return it in the onCreateView() method.

Let's have a look at our source code.

    package com.tutorials.viewpagertabsgridview;

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.GridView;

    public class Europe extends Fragment{

      String[] countries={"England","Germany","Spain","Belgium","France","Italy","Ireland","Holland"};
       ArrayAdapter<String> adapter;
       GridView gv;

       @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         View rootView=inflater.inflate(R.layout.europe, null);

         gv=(GridView) rootView.findViewById(R.id.gridView1);

         adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,countries);

         gv.setAdapter(adapter);

        return rootView;
      }
    }

Our FragmentPager Adapter

This our FragmentPagerAdapter class.

This class derives from android.support.v4.app.FragmentPagerAdapter.

Here are the responsibilities of this class:

  1. Receive a android.support.v4.app.FragmentManager via the constructor and pass that FragmentManager to the base FragmentManager class.
  2. Define a method getItem() that receives that an integer to act as the position of each fragment. We then instantiate a bundle object and depending on the position put the current page into the bundle, set the bundle as an argument of each fragment, then return the fragment. The return fragment willl then be displayed on the selected tab.
  3. Return the total number of actionbar tabs.
    package com.tutorials.viewpagertabsgridview;

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;

    public class MyAdapter extends FragmentPagerAdapter {

      public MyAdapter(FragmentManager fm) {
        super(fm);
      }

      @Override
      public Fragment getItem(int pos) {
        Bundle info=new Bundle();

        switch (pos) {
        case 0:
          Asia asia=new Asia();
          info.putInt("currentPage", pos++);
          asia.setArguments(info);
          return asia;
        case 1:
          Africa africa=new Africa();
          info.putInt("currentPage", pos++);
          africa.setArguments(info);
          return africa;
        case 2:
          Europe eu=new Europe();
          info.putInt("currentPage", pos++);
          eu.setArguments(info);
          return eu;

        }

        return null;
      }

      @Override
      public int getCount() {
        // TODO Auto-generated method stub
        return 3;
      }

    }

Our MainActivity

This is our main and only activity.

Activities are android components that represent a screen which the user interacts with.
If you are interacting with any android app visually then you are using an activity.
All those buttons, edittexts, gridviews etc are hosted by an activity.

In fact even the Fragment itself is hosted by an activity.

Here are Functionalities offered by this MainActivity.java file in detail.

  1. Define a package to host our class. In java classes get grouped into packages. This allows for easier management of these classes and provides a better implementation of Object Oriented Concepts.
  2. Add functionalities from other packages using the import statement. We need code libraries that have been wriiten already by other developers. Why? Well this saves us time by us not having to re-invent the wheel everytime by writing tens to hundreds of thousands of lines of code. Also we may not be at the skill level where we would write everything by ourselves. Hence we utilize import to import code written by experienced or even smarter developers.
  3. Create our class. This we do using class MainActivity..{} and we then make it public: public class MainActivity..{}. A piblic class can be accessed by other classes even those in different packages.
    package com.tutorials.viewpagertabsgridview;

    import android.app.ActionBar;
    import android.app.ActionBar.Tab;
    import android.app.ActionBar.TabListener;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.view.ViewPager;
    import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;

    public class MainActivity extends FragmentActivity {

      ActionBar ab;
      ViewPager vp;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            //ACTIONBAR
            ab=getActionBar();
            ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            ab.setDisplayShowTitleEnabled(true);

            vp=(ViewPager) findViewById(R.id.pager);

            FragmentManager fm=getSupportFragmentManager();

            //CREATE LISTENER
            ViewPager.SimpleOnPageChangeListener listener=new SimpleOnPageChangeListener()
            {
                public void onPageSelected(int position) {

                    ab.setSelectedNavigationItem(position);
                }
                };

                //ASSIGN LISTENER
                vp.setOnPageChangeListener(listener);

                //ADAPTER
                MyAdapter adapter=new MyAdapter(fm);
               vp.setAdapter(adapter);

             //TAB LSITENER
               ActionBar.TabListener tabListener=new TabListener() {

          @Override
          public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
            // TODO Auto-generated method stub

          }

          @Override
          public void onTabSelected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub
            vp.setCurrentItem(tab.getPosition());

          }

          @Override
          public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
            // TODO Auto-generated method stub

          }
        };
         //CRETAE TABS AND SET LISTENER
        Tab t=ab.newTab().setText("ASIA").setIcon(R.drawable.hourglass).setTabListener(tabListener);
        ab.addTab(t);

        t=ab.newTab().setText("Africa").setIcon(R.drawable.reports).setTabListener(tabListener);
        ab.addTab(t);

        t=ab.newTab().setText("Europe").setIcon(R.drawable.selecter).setTabListener(tabListener);
        ab.addTab(t);

        }

    }

Section 4 : Layouts

These are our XML layouts. These layouts will get inflated into Fragments.

(a). ActivityMain.xml

This is our main activity layout.

We add our ViewPager here. Our ViewPager resides in the android.support.v4.view package.

We have to assign it a unique id so that we can reference it from our java code.

It's layout width and height will wrap content in that layout.

    <RelativeLayout 
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_paddingBottom="@dimen/activity_vertical_margin"
        android_paddingLeft="@dimen/activity_horizontal_margin"
        android_paddingRight="@dimen/activity_horizontal_margin"
        android_paddingTop="@dimen/activity_vertical_margin"
        tools_context=".MainActivity" >

        <android.support.v4.view.ViewPager
            android_id="@+id/pager"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            />

    </RelativeLayout>

(b). Asia Layout

This is our Asia Layout. This layout will render Asian countries.

These countries will be shown in a GridView.

We set the number of columns for our GridView using the numColumns attribute : android:numColumns="3".

At the root our XML layout we have a RelativeLayout whose width and height will match parent.

We then define a gridview just below it. We specify the following for our gridview :

  1. Id - To identify the GridView.
  2. Layout Width and Layout Height - To define the rectangular dimensions of our gridview.
  3. We also align it to the Left and Top by setting the layout_alignParentLeft and layout_alignParentTop attributes to true.
  4. The number of columns to render in our gridview.

Here's our code:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        android_layout_width="match_parent"
        android_layout_height="match_parent" >

        <GridView
            android_id="@+id/gridView1"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_layout_alignParentTop="true"
            android_numColumns="3" >
        </GridView>

    </RelativeLayout>

(c). Africa Layout

This is our Africa Layout. This layout will render African countries.

These countries will be shown in a GridView.

We set the number of columns for our GridView using the numColumns attribute : android:numColumns="3".

At the root our XML layout we have a RelativeLayout whose width and height will match parent.

We then define a gridview just below it. We specify the following for our gridview :

  1. Id - To identify the GridView.
  2. Layout Width and Layout Height - To define the rectangular dimensions of our gridview.
  3. We also align it to the Left and Top by setting the layout_alignParentLeft and layout_alignParentTop attributes to true.
  4. The number of columns to render in our gridview.

Here's the code.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        android_layout_width="match_parent"
        android_layout_height="match_parent" >

        <GridView
            android_id="@+id/gridView1"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_layout_alignParentLeft="true"
            android_numColumns="3" >
        </GridView>

    </RelativeLayout>

(d). Europe Layout

This is our European Layout. This layout will render European countries.

These countries will be rendered in a GridView.

We set the number of columns for our GridView using the numColumns attribute : android:numColumns="3".

At the root we have a RelativeLayout whose width and height will match parent.

This means that the RelativeLayout's dimensions will match the whole application screen.

We then define a gridview just below it. We specify the following for our gridview :

  1. Id - To identify the GridView.
  2. Layout Width and Layout Height - To define the rectangular dimensions of our gridview.
  3. We also align it to the Left and Top by setting the layout_alignParentLeft and layout_alignParentTop attributes to true.
  4. The number of columns to render in our gridview.

Here's the code.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        android_layout_width="match_parent"
        android_layout_height="match_parent" >

        <GridView
            android_id="@+id/gridView1"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_layout_alignParentLeft="true"
            android_layout_alignParentTop="true"
            android_numColumns="3" >
        </GridView>

    </RelativeLayout>

Conclusion

So we have seen how to create a swipeable tabs application containg fragments with gridview. Our GridViews were showing a list of countries from Asia, Europe and Africa. We've made use of ActionBar Tabs. Those Tabs have clickable so users can certainly navigate by clicking them.

On the other hand we've used ViewPager to enable swipeability of our Fragments.