{"id":554,"date":"2017-10-17T03:43:03","date_gmt":"2017-10-17T03:43:03","guid":{"rendered":"http:\/\/abhiandroid.com\/materialdesign\/?page_id=554"},"modified":"2019-06-14T12:53:29","modified_gmt":"2019-06-14T12:53:29","slug":"viewpager","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/materialdesign\/viewpager","title":{"rendered":"ViewPager Tutorial With Example In Android Studio [Step by Step]"},"content":{"rendered":"<p>ViewPager in Android is a class that allows the user to flip left and right through pages of data. This class provides the functionality to flip pages in app.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-559\" src=\"\/materialdesign\/wp-content\/uploads\/2017\/10\/ViewPager-In-Android.gif\" alt=\"ViewPager In Android\" width=\"210\" height=\"250\" \/>It is a widget found in the support library. To use it you\u2018ll have to put the element inside your XML layout file that\u2019ll contain multiple child views. It is similar to what a ListAdapter does for a ListView.<\/p>\n<p>ViewPager is most often used along with fragment which is convenient way to manage the life cycle of each page. ViewPager class works with PagerAdapter which provides pages.<\/p>\n<hr \/>\n<h4><strong>Basic ViewPager XML Code:<\/strong><\/h4>\n<pre>&lt;android.support.v4.view.ViewPager\r\nandroid:id=\"@+id\/viewpager\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\napp:layout_behavior=\"@string\/appbar_scrolling_view_behavior\" \/&gt;<\/pre>\n<hr \/>\n<h4><strong>Steps For Implementing ViewPager:<\/strong><\/h4>\n<p>There are three important steps to implement ViewPager:<\/p>\n<p>1.) A layout(that contains ViewPager) for the MainActivity.<br \/>\n2.) FragmentPagerAdapter\/FragmentStatePagerAdapter class which controls the fragments to be shown on page swipes.<br \/>\n3.) Fragments to be shown on swiping the screen.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-592\" src=\"\/materialdesign\/wp-content\/uploads\/2017\/10\/ViewPager-in-Android-1024x470.jpg\" alt=\"ViewPager in Android\" width=\"660\" height=\"303\" srcset=\"https:\/\/abhiandroid.com\/materialdesign\/wp-content\/uploads\/2017\/10\/ViewPager-in-Android-1024x470.jpg 1024w, https:\/\/abhiandroid.com\/materialdesign\/wp-content\/uploads\/2017\/10\/ViewPager-in-Android-300x138.jpg 300w, https:\/\/abhiandroid.com\/materialdesign\/wp-content\/uploads\/2017\/10\/ViewPager-in-Android-768x353.jpg 768w, https:\/\/abhiandroid.com\/materialdesign\/wp-content\/uploads\/2017\/10\/ViewPager-in-Android.jpg 1063w\" sizes=\"auto, (max-width: 660px) 100vw, 660px\" \/><\/p>\n<hr \/>\n<h4><strong>PagerAdapter In ViewPager:<\/strong><\/h4>\n<p>There is a base class called PagerAdapter providing the adapter to populate pages inside of a ViewPager.<\/p>\n<p><strong>When you implement a PagerAdapter, you must override the following methods at minimum:<\/strong><\/p>\n<p><strong>1. instantiateItem(ViewGroup, int):<\/strong> This method should create the page for the given position\u00a0passed to it as an argument. We\u00a0inflate()\u00a0our layout resource to create the hierarchy of view objects and then set resource for the ImageView in it. Finally, the inflated view is added to the container (which should be the ViewPager) and return it as well.<\/p>\n<pre>public Object instantiateItem(ViewGroup container, int position) {\r\n View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);\r\n\r\nImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);\r\n imageView.setImageResource(mResources[position]);\r\n\r\ncontainer.addView(itemView);\r\n\r\nreturn itemView;\r\n }<\/pre>\n<p><strong>2. destroyItem(ViewGroup, int, Object):<\/strong> Removes the page from the container for the given position. We simply removed object using\u00a0removeView\u00a0but could\u2019ve also used\u00a0removeViewAt()\u00a0by passing it the position.<\/p>\n<pre> public void destroyItem(ViewGroup container, int position, Object object) {\r\n   container.removeView((LinearLayout)object);\r\n  }<\/pre>\n<p><strong>3. getCount():<\/strong> This method should return the number of views available, i.e., number of pages to be displayed\/created in the ViewPager.<\/p>\n<pre>public int getCount() {\r\n   return mResources.length;\r\n }<\/pre>\n<p><strong>4. isViewFromObject(View, Object):<\/strong> The object returned by\u00a0instantiateItem()\u00a0is a key\/identifier. This method checks whether the View passed to it (representing the page) is associated with that key or not. It is required by a PagerAdapter \u00a0to function properly.<\/p>\n<pre>  public boolean isViewFromObject(View view, Object object) {\r\n   return view == object;\r\n  }<\/pre>\n<hr \/>\n<h4><strong>Implementation Of PagerAdapter:<\/strong><\/h4>\n<p>PagerAdapter is responsible for creating the content of each page. You\u2019ll most likely want to use one of the following two implementation of\u00a0PagerAdapter:<\/p>\n<p><strong>Using FragmentPagerAdapter To Implement PagerAdapter:<\/strong><\/p>\n<p>1. Usually to display sliding fragments two methods of FragmentPagerAdapter are used, getCount() and getItem(). The first one returns the number of fragments to be displayed, and the second one is used to display the actual fragment &amp; it should be used when we need to store the whole fragment in memory.<\/p>\n<p>2. It is an implementation of PagerAdapter class that represents each page as Fragment that is persistently kept in the fragment manager as long as the user can return to the page, hence best to use when there\u2019s a fixed small set of screens to be navigated through.<\/p>\n<p>3. It works even better when the content of the fragments are static than something that constantly changes or gets updated.<\/p>\n<p>4. When using FragmentPagerAdapter the host ViewPager must have a valid ID set. It stores the previous data which is fetched from the adapter. It stores the whole fragment in memory and could increase a memory overhead if large amount of fragments are used in the ViewPager.<\/p>\n<p><strong>FragmentPagerAdapter code:<\/strong><\/p>\n<pre>class ViewPagerAdapter extends FragmentPagerAdapter {\r\n\u00a0 \u00a0 private final List mFragmentList = new ArrayList&lt;&gt;();\r\n\u00a0 \u00a0 private final List mFragmentTitleList = new ArrayList&lt;&gt;();\r\n\u00a0\r\n\u00a0 \u00a0 public ViewPagerAdapter(FragmentManager manager)\r\n\u00a0 \u00a0 \u00a0\u00a0super(manager);\r\n\u00a0 \u00a0 \u00a0 }\r\n\u00a0\r\n\u00a0 \u00a0 \u00a0 @Override\r\n\u00a0 \u00a0 \u00a0 public Fragment getItem(int position) {\r\n\u00a0 \u00a0 \u00a0\u00a0return mFragmentList.get(position);\r\n\u00a0 \u00a0 \u00a0 }\r\n\u00a0\r\n\u00a0 \u00a0 \u00a0 \u00a0@Override\r\n\u00a0 \u00a0 \u00a0 \u00a0public int getCount() {\r\n\u00a0 \u00a0 \u00a0 \u00a0return mFragmentList.size();\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0public void addFrag(Fragment fragment, String title) {\r\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0\u00a0mFragmentList.add(fragment);\r\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0\u00a0mFragmentTitleList.add(title);\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0@Override\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0public CharSequence getPageTitle(int position) {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return mFragmentTitleList.get(position);\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0\u00a0\u00a0}<\/pre>\n<p><strong>Using FragmentStatePagerAdapter For Implementation Of PagerAdapter:<\/strong><\/p>\n<p>1. Each page is a fragment which gets destroyed as soon as it\u2019s not visible to the user, i.e. keeping the saved state of that fragment. Due to this behavior it consumes much less memory .<\/p>\n<p>2. It takes the new value from the adapter every-time it is executed. It only stores the savedInstanceState of fragments, and destroys all the fragments when they lose focus.<\/p>\n<p>3. It should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState. Also it won&#8217;t affect the performance even if there are large number of fragments.<\/p>\n<p><strong><span style=\"color: #ff0000;\">Important Note &#8211;<\/span> In simple words, if your ViewPager is having few fixed number of Tabs say 3 or 4 use FragmentPagerAdapter. If it has more Tabs or endless number of Tabs then use FragmentStatePagerAdapter. ViewPager is mainly used for creating Sliding tabs.<\/strong><\/p>\n<hr \/>\n<h4><strong>PagerTitleStrip:<\/strong><\/h4>\n<p>You can add PagerTitleStrip to ViewPager in layout xml file to display title for each page. PagerTitleStrip helps to identify previous, current and next pages of a viewpager. PagerTitleStrip displays next, current and previous page titles of view pager at top or bottom of the screen. PagerTitleStrip gets page title from view pager adapter.<\/p>\n<p>The <strong>getPageTitle()<\/strong> method supplies a title to the page title strip that appears at the top of the screen.<\/p>\n<pre>@Override \r\npublic CharSequence getPageTitle(int position) { \r\nreturn mFragmentTitleList.get(position); }<\/pre>\n<p>Optional you can also include this code in the activity_main.xml<i>\u00a0<\/i>file:<\/p>\n<pre>&lt;android.support.v4.view.PageTitleStrip\r\nandroid:id=\"@+id\/pager_title_strip\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_gravity=\"top:\r\nandroid:background=\"#008080\"\r\nandroid:paddingBottom=\"4dp\"\r\nandroid:paddingTop=\"4dp\"\r\nandroid:textColor=\"#FFFFFF\"\r\n\/&gt;<\/pre>\n<hr \/>\n<h4><strong>ViewPager Example Using Fragments in Android Studio:<\/strong><\/h4>\n<p><strong>Example 1 &#8211; ViewPager With Fragment<\/strong><\/p>\n<p>Below is the first example example of ViewPager in which we will learn how to create a simple ViewPager Tabs with four Fixed Tabs using\u00a0FragmentPagerAdapter.<\/p>\n<p>Below you can download code, see final output and step by step explanation of the basic Pull To refresh example.<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"http:\/\/www.mediafire.com\/file\/281ctc1i1cu4cfm\/ViewPagerfragment.zip\/file\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><strong><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-588\" src=\"\/materialdesign\/wp-content\/uploads\/2017\/10\/ViewPager-Fragment-Example-In-Android-Studio.gif\" alt=\"ViewPager Fragment Example In Android Studio\" width=\"210\" height=\"282\" \/>Step 1<\/strong> : Create a new project and name it ViewPagerExample.<\/p>\n<p><strong>Step 2<\/strong>: Download four images, Apple, Orange, Banana and Grapes from the web. Now save those images in the drawable folder of your project.<\/p>\n<p><strong>Step 3:\u00a0<\/strong>Open res -&gt; layout -&gt;activity_main.xml (or) main.xml and add following code:<\/p>\n<p>In this step we add the code for using ViewPager with TabLayout having fixed tab.<\/p>\n<pre>&lt;android.support.design.widget.CoordinatorLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n xmlns:app=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"match_parent\"&gt;\r\n\r\n&lt;android.support.design.widget.AppBarLayout\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"wrap_content\"\r\n android:theme=\"@style\/ThemeOverlay.AppCompat.Dark.ActionBar\"&gt;\r\n\r\n&lt;android.support.v7.widget.Toolbar\r\n android:id=\"@+id\/toolbar\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"?attr\/actionBarSize\"\r\n android:background=\"?attr\/colorPrimary\"\r\n app:layout_scrollFlags=\"scroll|enterAlways\"\r\n app:popupTheme=\"@style\/ThemeOverlay.AppCompat.Light\" \/&gt;\r\n\r\n&lt;android.support.design.widget.TabLayout\r\n android:id=\"@+id\/tabs\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"wrap_content\"\r\n app:tabMode=\"fixed\"\r\n app:tabGravity=\"fill\"\/&gt;\r\n &lt;\/android.support.design.widget.AppBarLayout&gt;\r\n\r\n&lt;android.support.v4.view.ViewPager\r\n android:id=\"@+id\/viewpager\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"match_parent\"\r\n app:layout_behavior=\"@string\/appbar_scrolling_view_behavior\" \/&gt;\r\n &lt;\/android.support.design.widget.CoordinatorLayout&gt;<\/pre>\n<p><strong>Step 4:<\/strong>\u00a0Open\u00a0 \u00a0src -&gt; package -&gt; MainActivity.java and add the following code:<\/p>\n<p>In this step we are using the following methods:<\/p>\n<p><strong>tabLayout.setupWithViewPager()<\/strong>\u00a0\u2013 Assigns the ViewPager to TabLayout.<\/p>\n<p><strong>setupViewPager()\u00a0<\/strong>\u2013 Defines the number of tabs by setting appropriate fragment and tab name.<\/p>\n<p><strong>ViewPagerAdapter<\/strong>\u00a0\u2013 Custom adapter class provides fragments required for the ViewPager.<\/p>\n<p><strong>setupTabIcons()<\/strong>: added a method in which I have set all the tab icons.<\/p>\n<pre>package com.abhiandroid.viewpagerexample.myapplication;\r\n\r\nimport android.os.Bundle;\r\nimport android.support.design.widget.TabLayout;\r\nimport android.support.v4.app.Fragment;\r\nimport android.support.v4.app.FragmentManager;\r\nimport android.support.v4.app.FragmentPagerAdapter;\r\nimport android.support.v4.view.ViewPager;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.support.v7.widget.Toolbar;\r\nimport android.view.Menu;\r\nimport android.view.MenuItem;\r\nimport android.view.Window;\r\nimport android.view.WindowManager;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\n    private TabLayout tabLayout;\r\n    private ViewPager viewPager;\r\n    private int[] tabIcons = {\r\n            R.drawable.apple,\r\n            R.drawable.orange,\r\n            R.drawable.grapes,\r\n            R.drawable.banana\r\n    };\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\r\n        setSupportActionBar(toolbar);\r\n\r\n\r\n        viewPager = (ViewPager) findViewById(R.id.viewpager);\r\n        addTabs(viewPager);\r\n\r\n        tabLayout = (TabLayout) findViewById(R.id.tabs);\r\n        tabLayout.setupWithViewPager(viewPager);\r\n        setupTabIcons();\r\n\r\n    }\r\n    private void setupTabIcons() {\r\n        tabLayout.getTabAt(0).setIcon(tabIcons[0]);\r\n        tabLayout.getTabAt(1).setIcon(tabIcons[1]);\r\n        tabLayout.getTabAt(2).setIcon(tabIcons[2]);\r\n       tabLayout.getTabAt(3).setIcon(tabIcons[3]);\r\n    }\r\n    private void addTabs(ViewPager viewPager) {\r\n        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());\r\n        adapter.addFrag(new AppleFragment(), \"APPLE\");\r\n        adapter.addFrag(new OrangeFragment(), \"ORANGE\");\r\n        adapter.addFrag(new GrapesFragment(), \"GRAPES\");\r\n        adapter.addFrag(new BananaFragment(), \"Banana\");\r\n        viewPager.setAdapter(adapter);\r\n    }\r\n\r\n    class ViewPagerAdapter extends FragmentPagerAdapter {\r\n        private final List&lt;Fragment&gt; mFragmentList = new ArrayList&lt;&gt;();\r\n        private final List&lt;String&gt; mFragmentTitleList = new ArrayList&lt;&gt;();\r\n\r\n        public ViewPagerAdapter(FragmentManager manager) {\r\n            super(manager);\r\n        }\r\n\r\n        @Override\r\n        public Fragment getItem(int position) {\r\n            return mFragmentList.get(position);\r\n        }\r\n\r\n        @Override\r\n        public int getCount() {\r\n            return mFragmentList.size();\r\n        }\r\n\r\n        public void addFrag(Fragment fragment, String title) {\r\n            mFragmentList.add(fragment);\r\n            mFragmentTitleList.add(title);\r\n        }\r\n\r\n        @Override\r\n        public CharSequence getPageTitle(int position) {\r\n            return mFragmentTitleList.get(position);\r\n        }\r\n    }\r\n\r\n\r\n}<\/pre>\n<p><strong>Step 5:\u00a0<\/strong>Now create 4 xml layouts by\u00a0right clicking on res\/layout -&gt; New -&gt; Layout Resource\u00a0File\u00a0and name them as fragment_apple.xml, fragment_orange.xml,\u00a0fragment_grapes.xml and fragment_banana.xml and add the following code in respective files.<\/p>\n<p><strong>fragment_apple.xml:<\/strong><\/p>\n<pre>&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"match_parent\"&gt;\r\n\r\n&lt;TextView\r\n android:layout_width=\"wrap_content\"\r\n android:layout_height=\"wrap_content\"\r\n android:text=\"Apple\"\r\n android:textSize=\"40dp\"\r\n android:textStyle=\"bold\"\r\n android:layout_centerInParent=\"true\"\/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><strong>fragment_orange.xml<\/strong><\/p>\n<pre>&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    &gt;\r\n\r\n    &lt;TextView\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:text=\"Orange\"\r\n        android:textSize=\"40dp\"\r\n        android:textStyle=\"bold\"\r\n        android:layout_centerInParent=\"true\"\/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><strong>fragment_grapes.xml<\/strong><\/p>\n<pre>&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"&gt;\r\n\r\n    &lt;TextView\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:text=\"Grapes\"\r\n        android:textSize=\"40dp\"\r\n        android:textStyle=\"bold\"\r\n        android:layout_centerInParent=\"true\"\/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><strong>fragment_banana.xml<\/strong><\/p>\n<pre>&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    &gt;\r\n\r\n    &lt;TextView\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:text=\"Banana\"\r\n        android:textSize=\"40dp\"\r\n        android:textStyle=\"bold\"\r\n        android:layout_centerInParent=\"true\"\/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><strong>Step 6:<\/strong> Now we need 4 fragments, so we will create them one by one by right click on package folder and create classes and name them as AppleFragment, OrangeFragment,\u00a0GrapesFragment and BananaFragment and add the following code respectively.<\/p>\n<p><strong>AppleFragment.java<\/strong><\/p>\n<pre>package com.abhiandroid.viewpagerexample.myapplication;\r\n\r\n import android.os.Bundle;\r\n import android.support.v4.app.Fragment;\r\n import android.view.LayoutInflater;\r\n import android.view.View;\r\n import android.view.ViewGroup;\r\n\r\npublic class AppleFragment extends Fragment {\r\n\r\npublic AppleFragment() {\r\n \/\/ Required empty public constructor\r\n }\r\n\r\n@Override\r\n public void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n }\r\n\r\n@Override\r\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\r\n Bundle savedInstanceState) {\r\n \/\/ Inflate the layout for this fragment\r\n return inflater.inflate(R.layout.fragment_apple, container, false);\r\n }\r\n\r\n}\r\n<\/pre>\n<p><strong>OrangeFragment.java<\/strong><\/p>\n<pre>package com.abhiandroid.viewpagerexample.myapplication;\r\n\r\nimport android.os.Bundle;\r\nimport android.support.v4.app.Fragment;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\n\r\npublic class OrangeFragment extends Fragment {\r\n    \r\n    public OrangeFragment() {\r\n        \/\/ Required empty public constructor\r\n    }\r\n\r\n    @Override\r\n    public void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n    }\r\n\r\n    @Override\r\n    public View onCreateView(LayoutInflater inflater, ViewGroup container,\r\n                             Bundle savedInstanceState) {\r\n        \/\/ Inflate the layout for this fragment\r\n        return inflater.inflate(R.layout.fragment_orange, container, false);\r\n    }\r\n    \r\n}<\/pre>\n<p><strong>GrapesFragment.java<\/strong><\/p>\n<pre>package com.abhiandroid.viewpagerexample.myapplication;\r\n\r\nimport android.os.Bundle;\r\nimport android.support.v4.app.Fragment;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\n\r\npublic class GrapesFragment extends Fragment {\r\n\r\n    public GrapesFragment() {\r\n        \/\/ Required empty public constructor\r\n    }\r\n\r\n    @Override\r\n    public void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n    }\r\n\r\n    @Override\r\n    public View onCreateView(LayoutInflater inflater, ViewGroup container,\r\n                             Bundle savedInstanceState) {\r\n        \/\/ Inflate the layout for this fragment\r\n        return inflater.inflate(R.layout.fragment_grapes, container, false);\r\n    }\r\n}<\/pre>\n<p><strong>BananaFragment.java<\/strong><\/p>\n<pre>package com.abhiandroid.viewpagerexample.myapplication;\r\n\r\nimport android.os.Bundle;\r\nimport android.support.v4.app.Fragment;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\n\r\npublic class BananaFragment extends Fragment {\r\n\r\n    public BananaFragment() {\r\n        \/\/ Required empty public constructor\r\n    }\r\n\r\n    @Override\r\n    public void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n    }\r\n\r\n    @Override\r\n    public View onCreateView(LayoutInflater inflater, ViewGroup container,\r\n                             Bundle savedInstanceState) {\r\n        \/\/ Inflate the layout for this fragment\r\n        return inflater.inflate(R.layout.fragment_banana, container, false);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Now run the project and slide left to right or vice versa to see how ViewPager works.<\/p>\n<hr \/>\n<h4><strong>ViewPager Example 2 In Android Studio:\u00a0<\/strong><\/h4>\n<p>Below is the example of ViewPager in Android. We are going to create an AppCompatActivity, add a ViewPager reference and a FragmentPagerAdapter that will help us to navigate between the Fragments. Then, we are going to make instances of Fragments that will be added in our Adapter. The Android ViewPager has default swipe-gestures from one \u201cscreen\u201d to another.<\/p>\n<p>Below you can download code, see final output and step by step explanation of the basic Pull To refresh example.<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/ViewPager\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><strong><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-590\" src=\"\/materialdesign\/wp-content\/uploads\/2017\/10\/Viewpager-Example-In-Android-Studio.gif\" alt=\"Viewpager Example In Android Studio\" width=\"224\" height=\"342\" \/>Step 1:<\/strong> Create a new project and name it AndroidViewPagerExample.<\/p>\n<p><strong>Step 2<\/strong>: Download three images Apple,Orange and Grapes from the web. Now save those images in the drawable folder of your project.<\/p>\n<p><strong>Step 3:<\/strong>\u00a0Now open res -&gt; layout -&gt; activity_main.xml and add following code:<\/p>\n<p>Add a new xml file inside\/res\/layoutfolder, with name activity_main.xml. We should have the \/res\/layout\/activity_main.xml file that consists of a LinearLayout with vertical orientation, that includes a ViewPager.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n &lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n xmlns:custom=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"match_parent\"\r\n android:layout_gravity=\"center\"\r\n android:background=\"@drawable\/backround_blue\"\r\n android:orientation=\"vertical\"&gt;\r\n\r\n&lt;android.support.v4.view.ViewPager\r\n android:id=\"@+id\/pager\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"match_parent\"\r\n android:layout_gravity=\"center\"\r\n tools:context=\".MainActivity\"\/&gt;\r\n\r\n&lt;\/LinearLayout&gt;<\/pre>\n<p><strong>Step 4<\/strong>: Add a new xml file inside\/res\/drawable, with name activity <strong>backround_blue.xml<\/strong>. It is for setting the background.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;shape xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"&gt;\r\n&lt;gradient\r\n    android:angle=\"90\"\r\n    android:endColor=\"#3124dc\"\r\n    android:startColor=\"#062539\"\r\n    android:type=\"linear\" \/&gt;\r\n&lt;\/shape&gt;<\/pre>\n<p><strong>Step 5<\/strong>: Now open app\u00a0-&gt; java -&gt; package -&gt;\u00a0MainActivity.java and add the following code:<br \/>\n<strong>MainActivity.java<\/strong><\/p>\n<p>This is the Activity in which we are going to create a ViewPager instance and set its FragmentPagerAdapter. It is used to display sliding fragments. Two methods of FragmentPagerAdapter are used, <strong><em>getCount<\/em><\/strong>(returns the number of fragments to be displayed) and <strong><em>getItem<\/em><\/strong>(used to display the actual fragment).<\/p>\n<pre>package com.abhiandroid.viewpagerexample;\r\n\r\n import android.support.v4.app.FragmentManager;\r\n import android.support.v4.app.FragmentPagerAdapter;\r\n import android.os.Bundle;\r\n import android.support.v4.view.ViewPager;\r\n import android.support.v7.app.AppCompatActivity;\r\n\r\n import com.abhiandroid.viewpagerexample.myapplication1.R;\r\n\r\n public class MainActivity extends AppCompatActivity {\r\n \r\n@Override\r\n protected void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n setContentView(R.layout.activity_main);\r\n\r\n ViewPager pager = (ViewPager) findViewById(R.id.pager);\r\n pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));\r\n }\r\n\r\n private class MyPagerAdapter extends FragmentPagerAdapter {\r\n\r\n public MyPagerAdapter(FragmentManager fm) {\r\n super(fm);\r\n }\r\n\r\n@Override\r\n public android.support.v4.app.Fragment getItem(int pos) {\r\n switch (pos) {\r\n case 0:\r\n return FragmentViewPager.newInstance(getString(R.string.title_section1),    R.drawable.apple);\r\n case 1:\r\n return FragmentViewPager.newInstance(getString(R.string.title_section2), R.drawable.orange);\r\n case 2:\r\n return FragmentViewPager.newInstance(getString(R.string.title_section3), R.drawable.grapes);\r\n default:\r\n return FragmentViewPager.newInstance(getString(R.string.title_section1), R.drawable.apple);\r\n }\r\n }\r\n\r\n@Override\r\n public int getCount() {\r\n return 3;\r\n }\r\n }\r\n<\/pre>\n<p><strong>Step 6:<\/strong>\u00a0Create the layout of the main FragmentViewPager<br \/>\nAdd a new xml file inside\u00a0\/res\/layout\u00a0folder, with name <strong>fragment_main.xml.<\/strong> We should have the\u00a0<strong>\/res\/layout\/fragment_main.xml file<\/strong><\/p>\n<p>It is a simple layout xml for the FragmentViewPager.class, that consists of a LinearLayout with vertical orientation, that includes a TextView and an ImageView.<\/p>\n<pre>&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"match_parent\"\r\n android:background=\"#00000000\"\r\n android:orientation=\"vertical\"&gt;\r\n\r\n&lt;TextView\r\n android:id=\"@+id\/title\"\r\n android:layout_width=\"wrap_content\"\r\n android:layout_height=\"wrap_content\"\r\n android:layout_gravity=\"center\"\r\n android:layout_marginTop=\"44dp\"\r\n android:textColor=\"#ffffff\"\r\n android:textSize=\"60dp\" \/&gt;\r\n\r\n&lt;ImageView\r\n android:id=\"@+id\/image\"\r\n android:layout_width=\"wrap_content\"\r\n android:layout_height=\"wrap_content\"\r\n android:layout_gravity=\"center\"\r\n android:layout_marginTop=\"44dp\" \/&gt;\r\n\r\n&lt;\/LinearLayout&gt;<\/pre>\n<p><strong>Step 7<\/strong>: Create the source code of the main FragmentViewPager support.v4.app.Fragment<\/p>\n<p><strong>FragmentViewPager.java<\/strong><\/p>\n<pre>package com.abhiandroid.viewpagerexample;\r\n\r\n\/**\r\n * Created by abhiandroid\r\n *\/\r\n\r\nimport android.os.Bundle;\r\n import android.view.LayoutInflater;\r\n import android.view.View;\r\n import android.view.ViewGroup;\r\n import android.widget.ImageView;\r\n import android.widget.TextView;\r\n\r\nimport com.abhiandroid.viewpagerexample.myapplication1.R;\r\n\r\npublic class FragmentViewPager extends android.support.v4.app.Fragment {\r\n\r\n@Override\r\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\r\n View v = inflater.inflate(R.layout.fragment_main, container, false);\r\n\r\nTextView tv = (TextView) v.findViewById(R.id.title);\r\n tv.setText(getArguments().getString(\"text\"));\r\n\r\nImageView imageView = (ImageView) v.findViewById(R.id.image);\r\n imageView.setBackgroundResource(getArguments().getInt(\"img\"));\r\n\r\nreturn v;\r\n }\r\n\r\npublic static FragmentViewPager newInstance(String text, int image) {\r\n\r\nFragmentViewPager f = new FragmentViewPager();\r\n Bundle b = new Bundle();\r\n b.putString(\"text\", text);\r\n b.putInt(\"img\", image);\r\n\r\nf.setArguments(b);\r\n\r\nreturn f;\r\n }\r\n }<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Now run the project and swipe from left to right or vice versa to see different fruit names and images on screen.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>ViewPager in Android is a class that allows the user to flip left and right through pages of data. This class provides the functionality to flip pages in app. It is a widget found in the support library. To use it you\u2018ll have to put the element inside your XML layout file that\u2019ll contain multiple &hellip; <a href=\"https:\/\/abhiandroid.com\/materialdesign\/viewpager\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">ViewPager Tutorial With Example In Android Studio [Step by Step]<\/span><\/a><\/p>\n","protected":false},"author":5,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"home.php","meta":{"footnotes":""},"class_list":["post-554","page","type-page","status-publish","hentry"],"psp_head":"<title>ViewPager Tutorial With Example In Android Studio [Step by Step] \u2013 Android Material Design Tutorial<\/title>\r\n<meta name=\"description\" content=\"Follow our simple easy to grasp step by step tutorial on ViewPager with example in Android Studio. It is explained with Fragments and Fragments. ViewPager in Android is a class that allows the user to flip left and right through pages of data.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/materialdesign\/viewpager\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/pages\/554","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/comments?post=554"}],"version-history":[{"count":4,"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/pages\/554\/revisions"}],"predecessor-version":[{"id":755,"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/pages\/554\/revisions\/755"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/materialdesign\/wp-json\/wp\/v2\/media?parent=554"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}