{"id":1777,"date":"2014-10-11T22:49:44","date_gmt":"2014-10-11T17:19:44","guid":{"rendered":"http:\/\/codetheory.in\/?p=1777"},"modified":"2016-07-11T22:30:58","modified_gmt":"2016-07-11T17:00:58","slug":"android-swipe-views-with-tabs","status":"publish","type":"post","link":"https:\/\/codetheory.in\/android-swipe-views-with-tabs\/","title":{"rendered":"Android Swipe (Touch Gesture) Views Using ViewPager, FragmentPagerAdapter and FragmentStatePagerAdapter With Action Bar Tabs"},"content":{"rendered":"

Swipe Views<\/a> are an efficient way to allow the user to laterally navigate among related data items spread across multiple panes using a simple touch gesture (swipes\/flings), making access to data faster and much more enjoyable. Think of the android home screen where you can swipe across multiple sibling screens or the facebook or twitter app with multiple screens (and their respective tabs) where you can just swipe to navigate through them. The entire experience is super interactive and fun. They’re basically equivalent to slideshows\/carousels which has sections with\/without tabs (or similar controls to navigate) in the web development arena.<\/p>\n

<\/p>\n

Android provides us with the ViewPager<\/code><\/a> class that allows the user to flip left and right through pages of data. To use it, you’ll have to put the <ViewPager><\/code> element (from the support library<\/a>) inside your XML layout file that’ll contain multiple child views (which will be the different pages). This is how it’s done:<\/p>\n

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

Once this code is placed in say res\/layout\/activity_main.xml<\/code>, we’ll have to hook the layout to a PagerAdapter<\/code><\/a> which will populate our ViewPager<\/code> with pages. Basically a PagerAdapter<\/code> is responsible for creating the content for each page. You’ll most likely want to use one of the following two implementation of PagerAdapter<\/code>:<\/p>\n