Home Android Fragments : Show/Navigate via Tabs

Android Fragments : Show/Navigate via Tabs

Android Fragments : Show/Navigate via Tabs




Android Fragments Tab Navigation

Introduction

Have you ever had these types of scenaries which make you wonder how the world we live in is beautiful amidst the chaos of outer space.I was sitting just across my local University stadium yesterday at looking on as workers made the last touches on the pitch.The next week was inter university tournaments yet the place was serene and you couldn't imagine.This is a local university with a local stadium.The pitch is divided into several sections,basketball,hockey,soccer,volleyball etc.What blew my mind was in a small way this reflects the idea of fragments and activities.

Fragments are basically sub-activities.Just like,say basketball pitch is just a small section of the whole pitch.Just the basketball picth has its own rules and regulations,fragments are themselves standalone with their own lifecycle and view hierarchy.Fragments exist within activities context,as basketball pitch exists within the stadium.The fans who enter the stadium most likely won't care too much about how basketball pitch is just a small section.

Fragments were added by android team to the core classes in Android 3.0.We take a look at how to navigate them with tabs either by swiping or clicking the tabs.

 

What we do :

  • Make a simple app with 3 pages.
  • These 3 pages shall be fragments.
  • Each fragment shall have a simple image with a textview.
  • When user clicks a tab at the top,he navigates to the appropriate page.
  • He can also swipe from left or right.
  • This swiping is facilitated by a type of view called ViewPager.
  • Viewpager is in support.v4 libraries package.
  • The tabs shall be used for navigation by clicking.

What You do :

  • Create a project in android studio.
  • Give it a name and choose minimum and target SDKs.
  • Personally I used 15 and 23 as visible in my build.gradle below.
  • Then choose basic activity as your template layout.
  • All these are not requirements and you can choose whatever you like.

SECTION 1 : Our Dependencies

 

Build.Gradle

  • Thankfully Android Studio has added for us dependencies for AppCompat and Design support libraries.
  • Note we are subclassing AppCompatActivity in our MainActvity.
  • Design support libraries are for cordinatorlayout,appbar layout,and floating action button.All contained in our ActivityMain.xml layout specification.Toolbar uses support.v7.

 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.tutorials.hp.fixedtabs"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
}

SECTION 2 : Our Fragments

These fragments are our pages and we shall show them when tabs are clicked.Each fragment has its own view hierarchy.To facilitate this then we need to define layouts for each and add whatever views we like.In this case I only set the image background for each layout.The layouts shall then get inflated to the ffragment UI. In our case when a fragment is cast to string,by overriding the toString() method,we simply return the title of that fragment.This shall then get displayed as our tab title.

Crime Fragment

Main Responsibility : IS OUR CRIME PAGE

  • Shall get inflated from our crime fragment layout.
  • This shall represent crime page in our app.
  • We shall show a bad boy image in this fragment.
  • Shall be shown when Crime Tab is clicked.

 

package com.tutorials.hp.fixedtabs;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Hp on 3/22/2016.
 */
public class CrimeFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.crime_fragment,null);
        return rootView;
    }


    @Override
    public String toString() {
        return "Crime";
    }
}

 

 

 

Documentary Fragment

Main Responsibility : IS OUR DOCUMENTARY PAGE

  • Shall get inflated from our documentary fragment layout.
  • This shall represent documentary page in our app.
  • We shall show a shuttle carrier plane image in this fragment.
  • Shall be shown when Documentary Tab is clicked.
  • Woops.In reality its science fiction page not documentary I see.
package com.tutorials.hp.fixedtabs;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Hp on 3/22/2016.
 */
public class ScienceFictionFragment extends Fragment {

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

        View rootView=inflater.inflate(R.layout.science_fragment,null);
        return rootView;
    }

    @Override
    public String toString() {
        return "Science";
    }
}

Drama Fragment

Main Responsibility : IS OUR DRAMA PAGE

  • Shall get inflated from our drama fragment layout.
  • This shall represent drama page in our app.
  • We shall show a game of thrones character  image in this fragment.
  • Shall be shown when Drama Tab is clicked.
package com.tutorials.hp.fixedtabs;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Hp on 3/22/2016.
 */
public class DramaFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.drama_fragment,null);
        return rootView;
    }

    @Override
    public String toString() {
        return "Drama";
    }
}

SECTION 3 : Our Pager Adapter

FragmentPagerAdapter class.

Main Responsibility : BIND OUR FRAGMENTS TO OUR TABS.

  • Our pages we said shall be our fragments.
  • This class shall add them to our pages collection.
  • It shall also return each page when a tab is clicked.
  • We set the total count by returning the total number of fragments we have.
  • We also set the tab titles here.
package com.tutorials.hp.fixedtabs;

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

import java.util.ArrayList;

/**
 * Created by Hp on 3/22/2016.
 */
public class MyPagerAdapter extends FragmentPagerAdapter {

    ArrayList<Fragment> pages=new ArrayList<>();

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

    @Override
    public Fragment getItem(int position) {
        return pages.get(position);
    }

    @Override
    public int getCount() {
        return pages.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return pages.get(position).toString();
    }

    public void addPage(Fragment f)
    {
        pages.add(f);
    }
}

SECTION 4 : Our Activity

MainActivity class.

Main Responsibility : LAUNCH OUR APP.

  • The leader of all our classes.
  • It extends AppcompatActivity hence is an activity.
  • Activities are the entry point of android applications.This is no exception.
  • We shall reference the widgets like Tablayout here, and views like ViewPager,FloatingActionButton etc from our XML Layouts.
  • We then can either implement OnTabSelectedListener here explicitly on our class or just using an annonymous class.
  • We then set this listener to our tablayout.
  • Moreover we set other tablayout properties like gravity.
  • We also make sure that we instantiate our fragments and pass them to our adapter.Remember they are our pages we said.
  • Inside our annonymous class,we override some methods.
  • In this case we are only interested in OnTabSelected since we want to set the current item of our viewpager.
package com.tutorials.hp.fixedtabs;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private TabLayout tab;
    private ViewPager vp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        vp= (ViewPager) findViewById(R.id.viewpager);
        addPages(vp);

        tab= (TabLayout) findViewById(R.id.tabs);
        tab.setTabGravity(TabLayout.GRAVITY_FILL);
        tab.setupWithViewPager(vp);
        tab.setOnTabSelectedListener(tabSelectedListener(vp));


    }

  private void addPages(ViewPager viewPager)
  {
     MyPagerAdapter myPagerAdapter=new MyPagerAdapter(getSupportFragmentManager());
      myPagerAdapter.addPage(new CrimeFragment());
      myPagerAdapter.addPage(new DramaFragment());
      myPagerAdapter.addPage(new ScienceFictionFragment());

      vp.setAdapter(myPagerAdapter);
  }

    private TabLayout.OnTabSelectedListener tabSelectedListener(final  ViewPager pager)
    {
        return  new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                pager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        };
    }


}

SECTION 5 : Our Layouts

ActivityMain.xml Layout.

  • Inflated as our activity's view.
  • Includes our content main layout.
  • Contains support.v4 widgets like Cordinatorlayout, appbarlayout, toolbar and our floating action button view.
  • We also add our ViewPager here.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.fixedtabs.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

           />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        />

</android.support.design.widget.CoordinatorLayout>

ContentMain.xml Layout.

  • Shall get replaced by our fragments layouts.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.fixedtabs.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

CrimeFragment.xml Layout.

  • Contains Crime fragment View hierarchy.
  • Inflated to Crime fragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/red"
    >

</LinearLayout>

DramaFragment.xml Layout.

  • Contains Drama fragment View hierarchy.
  • Inflated to Drama fragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/breaking"
    >

</LinearLayout>

DocumentaryFragment.xml Layout.

  • Contains Documentary fragment View hierarchy.
  • Inflated to Documentary fragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/thrones"
    >

</LinearLayout>

SECTION 6 : Downloadable Source Reference

To be uploaded soon.

SECTION 7 : Our Result

LAST SECTION

Lets share more tips in OUR FB PAGE.

Cheers.

 

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    11 + two =

    Leave a Comment

    1 × 2 =