Android screen slide using ViewPager and Fragment

When you build an application that allows transitions between different modules or pages (screen slides), this Android tip is useful to you. I am going to show you how to achieve this goal using ViewPager and Fragment.

The ViewPager needs FragmentStatePagerAdapter abstract class to provide pages or instances of Fragment. So you have to Creates a class that extends the FragmentStatePagerAdapter abstract class and implements the getItem() method to supply instances of Fragment as new pages and the getCount() method which returns the number of pages the adapter will create. Then use the setAdapter() method with an instance of the derived class to bind pages to the ViewPager.

Now to have an example application on screen slides using ViewPager and Fragment, create a new Android project. Then modify the activity_main.xml file to add ViewPager widget shown below.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.andexamples.MainActivity" >

   <android.support.v4.view.ViewPager
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/pager"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

</RelativeLayout>



Next, create a class called SlidePageFragment that extends Fragment class in src folder and its layout file (frlayout.xml) in res/layout folder.

SlidePageFragment.java

package com.example.andexamples;
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.TextView;

public class SlidePageFragment extends Fragment{
static TextView tv;
static int page_pos=0;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.frlayout, container, false);
     tv=(TextView)rootView.findViewById(R.id.txtview);
     Bundle b=getArguments();
     page_pos=b.getInt("pos");
     tv.setText(MainActivity.str[page_pos]);
     return rootView;
   }
public static SlidePageFragment newInstance(int position){
SlidePageFragment instance= new SlidePageFragment();
Bundle barg=new Bundle();
barg.putInt("pos", position);
instance.setArguments(barg);
   return(instance);
}

}



In the code above, I use setArguments() method to pass an argument (page position) to the instance of the SlidePageFragment class. By doing, we can make sure that the position is always preserved although the fragment is re-created by the system. With the position, the content is assigned to the page correctly.

Frlayout.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >
   <TextView style="?android:textAppearanceMedium"
        android:id="@+id/txtview"
        android:padding="10dp"
        android:lineSpacingMultiplier="1.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/txtstr" />

</LinearLayout>



In the MainActivity class, you create a class called PagerAdapter extending FragmentStatePagerAdapter. You have to override the getItem() and getCount() methods. The getItem() method returns an instance of SlidePageFragment and the getCount() method return the number of pages. In this example, the number of pages is three.

In the onCreate() method of the MainActivity class, you make a reference to the ViewPager widget, create an instance of PagerAdapter, and set the adapter to the ViewPager using the setAdapter method.

Typically, without the user interaction (swiping right or left), the screen slideshow is not automatically performed. To cause the screen slideshow happen automatically, I use Handler and Runnable. The translation from one page to another page happens automatically after a specific amount of time elapses (10 seconds).


package com.example.andexamples;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends FragmentActivity {
int position;
public static String[] str;

   // the number of pages to show
  
   private static final int NUM_PAGES = 3;

   /*
   The pager widget that handles animation and allows swiping horizontally to access previous and next pages
   */
   private ViewPager vPager;

   // the pager adapter that provides the pages to the view pager widget

   private PagerAdapter pAdapter;
  
   private Handler handler=new Handler();
   private Runnable runnale=new Runnable(){
   public void run(){
   vPager.setCurrentItem(position,true);
   if(position>=NUM_PAGES ) position=0;
   else position++;
   // Move to the next page after 10s
   handler.postDelayed(runnale, 10000);
   }
   };
  
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize position variable used in auto slideshow
position=0;
// Initialize the array of page contents
str=getResources().getStringArray(R.array.page_content);
// Instantiate a ViewPager and a PagerAdapter
     vPager = (ViewPager) findViewById(R.id.pager);
     pAdapter = new PagerAdapter(getSupportFragmentManager());
     vPager.setAdapter(pAdapter);
}


   public void onBackPressed() {
     if (vPager.getCurrentItem() == 0) {
        // If the user is currently looking at the first step, allow the system to handle the
        // Back button. This calls finish() on this activity and pops the back stack.
        super.onBackPressed();
     } else {
        // Otherwise, select the previous step.
        vPager.setCurrentItem(vPager.getCurrentItem() - 1);
     }
   }
   // PagerAdater class that extends the FragmentStatePagerAdapter

   private class PagerAdapter extends FragmentStatePagerAdapter {
     public PagerAdapter(FragmentManager fm) {
        super(fm);
     }

     @Override
     public Fragment getItem(int pos) {
         return SlidePageFragment.newInstance(pos);
     }

     @Override
     public int getCount() {
        return NUM_PAGES;
     }
   }
public void onPause(){
super.onPause();
if(handler!=null)
handler.removeCallbacks(runnale);
}
public void onResume(){
super.onResume();
// Start auto screen slideshow after 1s
handler.postDelayed(runnale, 1000);
}

}


Before running the example application, you have to create a string-array that has three items in the strings.xml file. Each item of the string-array is the content of each page to display when the transitions between the pages happen.


<string-array name="page_content">
     <item>In this Android tip, I am going to show you how to make screen slideshow.
        First, modify the activity_main.xml file to add a ViewPager widget.
     </item>
     <item>
        Second, create a Fragment called SlidePageFragment and its layout file called frlayout.xml.
     </item>
     <item>
        Third, Creates a class called PagerAdapter that extends the FragmentStatePagerAdapter abstract class and implements the getItem() method to supply instances of SlidePageFragment as new pages and the getCount() method which returns the number of pages the adapter will create.
     </item>    
    
</string-array>

Android-screen-slide-using-ViewPager-and-Fragment

Posted by: Dara | post date: 10-17-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.