2.6.3 Simple Usage of ViewPager
Category Android Basic Tutorial
Introduction:
>
This section introduces ViewPager, a UI component introduced in Android 3.0. It's a tool for swiping through views. It's commonly used for app guides or image sliders. Since it was introduced in 3.0, you need to include the v4 compatibility library for use in lower versions. ViewPager can be found in the directory: android.support.v4.view.ViewPager. Below, we'll learn about its basic usage. Official API documentation: ViewPager
1. Introduction to ViewPager
>
ViewPager is a simple page-swiping component. We can fill it with multiple views and swipe left or right to switch between them. We can set animation effects for transitions using the setPageTransformer() method. However, since we haven't covered animations yet, we'll discuss setting animations for ViewPager in the next chapter on drawing and animations. Like ListView and GridView, ViewPager requires an Adapter to bind views to it. ViewPager has a specific Adapter called PagerAdapter. Google recommends using Fragments to populate ViewPager, making it easier to manage each page's lifecycle. Two specialized Adapters for Fragments are provided: FragmentPageAdapter and FragmentStatePagerAdapter. Let's briefly analyze the differences between these two Adapters:
-FragmentPageAdapter: Similar to PagerAdapter, it caches only the current Fragment and one on each side, totaling three Fragments. For example, with four pages (1, 2, 3, 4):
-FragmentStatePagerAdapter: When a Fragment is no longer visible, it is destroyed, saving only its state. A new page is generated when it needs to be displayed again.
In summary, FragmentPageAdapter is suitable for a small, fixed number of pages, while FragmentStatePagerAdapter is better for a large number of pages or complex pages that consume significant memory.
2. Using PagerAdapter
>
Let's start with the basic PagerAdapter. To use it, you need to override the following four methods. However, you only need to override getCount() and isViewFromObject() in practice.
-getCount(): Returns the number of views in the ViewPager.
-destroyItem(): Removes a page at a given position. The adapter is responsible for removing the view from the container. This ensures the view is removed by the time finishUpdate(viewGroup) returns.
The other two methods involve a key:
-instantiateItem():
- Adds the view for the given position to the container, creating and displaying it.
- Returns an Object (key) representing the new page. Typically, this is the view itself, but you can also define your own key, ensuring it corresponds uniquely to the view.
-isViewFromObject(): Determines if the key returned by instantiateItem(ViewGroup, int) corresponds to a view. Typically, you would write return view == object.
Example 1: Basic Usage
Screenshot:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="@+id/vpager_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<android.support.v4.view.PagerTabStrip
android:id="@+id/pagertitle"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_gravity="top"
android:textColor="#FFFFFF" />
</android.support.v4.view.ViewPager>
</LinearLayout>
And the layout where PagerTabStrip is located:
activity_three.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#C0C080"
android:gravity="center"
android:text="PagerTabStrip Effect Demonstration"
android:textSize="18sp" />
<android.support.v4.view.ViewPager
android:id="@+id/vpager_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<android.support.v4.view.PagerTabStrip
android:id="@+id/pagertitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top" />
</android.support.v4.view.ViewPager>
</LinearLayout>
Next, both are the same. We will first write a custom PagerAdapter. In addition to the four methods overridden earlier, we need to override another method: getPageTitle(), which sets the title. The code is as follows:
MyPagerAdapter2.java:
/**
* Created by Jay on 2015/10/8 0008.
*/
public class MyPagerAdapter2 extends PagerAdapter {
private ArrayList<View> viewLists;
private ArrayList<String> titleLists;
public MyPagerAdapter2() {}
public MyPagerAdapter2(ArrayList<View> viewLists, ArrayList<String> titleLists) {
this.viewLists = viewLists;
this.titleLists = titleLists;
}
@Override
public int getCount() {
return viewLists.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewLists.get(position));
return viewLists.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewLists.get(position));
}
@Override
public CharSequence getPageTitle(int position) {
return titleLists.get(position);
}
}
Finally, the Activity part, both are the same:
TwoActivity.java:
/**
* Created by Jay on 2015/10/8 0008.
*/
public class TwoActivity extends AppCompatActivity {
private ViewPager vpager_two;
private ArrayList<View> aList;
private ArrayList<String> sList;
private MyPagerAdapter2 mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
vpager_two = (ViewPager) findViewById(R.id.vpager_two);
aList = new ArrayList<View>();
LayoutInflater li = getLayoutInflater();
aList.add(li.inflate(R.layout.view_one, null, false));
aList.add(li.inflate(R.layout.view_two, null, false));
aList.add(li.inflate(R.layout.view_three, null, false));
sList = new ArrayList<String>();
sList.add("Orange");
sList.add("Light Yellow");
sList.add("Light Brown");
mAdapter = new MyPagerAdapter2(aList, sList);
vpager_two.setAdapter(mAdapter);
}
}
That's it, very simple. If you have any questions, download the demo and take a look.
Example 3: Using ViewPager to Achieve TabHost Effect:
>
Of course, Example 2 is often just for show and not very practical. In actual development, we might need to customize this title bar. Below, we will write a simple example to achieve the TabHost effect. If you don't know what TabHost is, then take a look at the screenshot!
Running Effect Diagram:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Light Brown"
android:textColor="#000000" />
</LinearLayout>
<ImageView
android:id="@+id/img_cursor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="matrix"
android:src="@mipmap/line" />
<android.support.v4.view.ViewPager
android:id="@+id/vpager_four"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="1.0"
android:flipInterval="30"
android:persistentDrawingCache="animation" />
</LinearLayout>
Now let's move on to our Activity and outline our approach:
-
Step 1: We need to center our moving block under the first text, so we need to calculate the offset: First, get the image width (pw), then get the screen width (sw). The calculation is straightforward: offset = ((sw / 3) - pw) / 2 // screen width / 3 - image width, then divide by 2 for both sides! one = offset * 2 + pw;two = one * 2;**
-
Step 2: When we swipe the page, our slider needs to move. We need to add an OnPageChangeListener event to the ViewPager. We need to determine the page after the swipe and record which page was active before the swipe. Below is a diagram I drew, which might make it easier to understand!
PS: It's been a long time since I last wrote, so the handwriting is ugly, but as long as it's legible, that's fine. Ugly handwriting, beautiful person, haha~
public void onPageScrolled(int i, float v, int i1) {
}
Well, you might not be familiar with animations, but don't worry, in the next chapter we'll guide you through it~
3. ViewPager with Fragment Example
>
In the previous chapter on Fragments, we covered an example usage: Android Basic Tutorial — 5.2.4 Fragment Example — Bottom Navigation Bar + ViewPager Page Swipe. We won't go into detail here, but you can click the link if you're interested~
4. Code Example Download
Summary:
>
Regarding ViewPager, due to space limitations, some aspects were not covered. You'll need to consult the documentation for further details.
Additionally, as mentioned above, ViewPager animations will be covered in the next chapter! That's all for now~
I had promised to complete the entire series during the National Day holiday, but unfortunately, I didn't write a single article. I apologize for that... My girlfriend came to visit, so, you know~
-1.0.1 2015 Latest Android Basic Tutorial Table of Contents
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android Apps with Eclipse + ADT + SDK
-1.2.2 Developing Android Apps with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Genymotion Emulator Installation
-1.5.1 Git Tutorial for Local Repository Operations
-1.5.2 Using GitHub to Set Up a Remote Repository
-1.6 How to Use 9-Patch Images
-1.7 Interface Prototype Design
-1.8 Project Source Analysis (Various Files, Resource Access)
-1.9 Android App Signing and Packaging
-1.11 Decompiling APK to Retrieve Code & Resources
-2.1 Concepts of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-2.2.2 RelativeLayout (Relative Layout)
-2.2.3 TableLayout (Table Layout)
-2.2.4 FrameLayout (Frame Layout)
-2.2.5 GridLayout (Grid Layout)
-2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 Detailed Explanation of TextView (Text Box)
-2.3.2 Detailed Explanation of EditText (Input Box)
-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton and Switch
-2.3.7 ProgressBar (Progress Bar)
-2.3.9 RatingBar (Star Rating Bar)
-2.4.1 ScrollView (Scroll Bar)
-2.4.2 Date & Time Components (Part 1)
-2.4.3 Date & Time Components (Part 2)
-2.4.5 Simple Usage of ListView
-2.4.6 Optimization of BaseAdapter
-2.4.7 Focus Issues with ListView
-2.4.8 Solving Checkbox Misalignment in ListView
-2.4.9 Data Update Issues with ListView
-2.5.0 Building a Reusable Custom BaseAdapter
-2.5.1 Implementing Multi-Layout ListView Items
-2.5.2 Basic Usage of GridView (Grid View)
-2.5.3 Basic Usage of Spinner (List Option Box)
-2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text Box)
-2.5.5 Basic Usage of ExpandableListView (Collapsible List)
-2.5.6 Basic Usage of ViewFlipper (Flip View)
-2.5.8 Detailed Explanation of Notification (Status Bar Notification)
-2.5.9 Detailed Explanation of AlertDialog (Dialog Box)
-2.6.0 Basic Usage of Other Common Dialogs
-2.6.1 Basic Usage of PopupWindow (Floating Box)
- 2.6.3 Simple Usage of ViewPager
-2.6.4 Simple Usage of DrawerLayout (Official Side Menu)
-3.1.1 Event Handling Mechanism Based on Listeners
-3.2 Event Handling Mechanism Based on Callbacks
-3.3 Analysis of Handler Message Passing Mechanism
-3.4 TouchListener vs OnTouchEvent + Multi-Touch
-3.5 Listening for Content Changes in EditText
-3.6 Responding to System Settings Events (Configuration Class)
-3.7 AsyncTask (Asynchronous Task)
-4.1.1 Introduction to Activity
-4.2.1 Introduction to Service
-4.3.1 Introduction to BroadcastReceiver
-4.3.2 In-Depth BroadcastReceiver
- 4.4.1 Introduction to ContentProvider
- 4.4.2 Deep Dive into ContentProvider — Document Provider
- 4.5.1 Basic Usage of Intent
- 4.5.2 Passing Complex Data with Intent
- 5.1 Basic Overview of Fragment
- 5.2.1 Fragment Example Walkthrough — Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example Walkthrough — Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example Walkthrough — Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example Walkthrough — Bottom Navigation Bar + ViewPager Swipe to Switch Pages
- 5.2.5 Fragment Example Walkthrough — Simple Implementation of News (Shopping) App List Fragment
- 6.1 Data Storage and Access — File Storage and Reading
- 6.2 Data Storage and Access — SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access — Introduction to SQLite Database
- 6.3.2 Data Storage and Access — Further Exploration of SQLite Database
- 7.1.1 Android Network Programming Essentials and HTTP Protocol Study
- 7.1.2 Learning Android HTTP Request and Response Headers
- 7.1.3 Android HTTP Request Methods: HttpURLConnection
- 7.1.4 Android HTTP Request Methods: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android Calling WebService
- 7.5.1 Basic Usage of WebView (Web View)
- 7.5.2 Basic Interaction Between WebView and JavaScript
- 7.5.3 Important Considerations for WebView After Android 4.4
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Error Code Information from Web Pages
- 7.6.1 Socket Learning Network Basics Preparation
- 7.6.2 Socket Communication Based on TCP Protocol (1)
- 7.6.3 Socket Communication Based on TCP Protocol (2)
- 7.6.4 Socket Communication Based on UDP Protocol
- 8.1.1 Summary of 13 Drawable Types in Android Part 1
- 8.1.2 Summary of 13 Drawable Types in Android Part 2
- 8.1.3 Summary of 13 Drawable Types in Android Part 3
- 8.2.1 Comprehensive Analysis of Bitmap (Bitmap) Part 1
- 8.2.2 OOM Issues Caused by Bitmap
- 8.3.1 Detailed Explanation of Three Drawing Tool Classes
- 8.3.2 Practical Examples of Drawing Classes
- 8.3.3 Paint API — MaskFilter (Mask)
- 8.3.4 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 1)
- 8.3.5 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 2)
- 8.3.6 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 3)
- 8.3.7 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 4)
- 8.3.8 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 5)
- 8.3.9 Paint API — ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API — ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API — ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API — PathEffect (Path Effect)
- 8.3.13 Paint API — Shader (Image Rendering)
- 8.3.14 Paint Enum/Constant Values and ShadowLayer Shadow Effect
- 8.3.15 Paint API — Typeface (Font Style)
- 8.3.16 Detailed Explanation of Canvas API (Part 1)
- 8.3.17 Detailed Explanation of Canvas API (Part 2) Clipping Methods Collection
- 8.3.18 Detailed Explanation of Canvas API (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Frame Animation in Android Animation Collection
- 8.4.2 Tween Animation in Android Animation Collection
- 8.4.3 Property Animation in Android Animation Collection — Introduction
- 8.4.4 Property Animation in Android Animation Collection — Further Exploration
- 9.1 Playing Sound Effects with SoundPool (Duang~)
- 9.2 MediaPlayer for Audio and Video Playback
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord for Audio Recording
- 10.1 TelephonyManager (Telephony Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Series (1) – Introduction
- 10.11 Sensor Series (2) – Orientation Sensor
- 10.12 Sensor Series (3) – Accelerometer/Gyroscope Sensor
- 10.12 Sensor Series (4) – Understanding Other Sensors
- 10.14 Introduction to Android GPS
- 11.0 Completion of the 2015 Latest Android Basic Beginner's Tutorial
- 12.1 Android Practice: DrySister Viewing Girls App (Version 1) – Project Setup and Simple Implementation
- 12.2 DrySister Viewing Girls App (Version 1) – 2. Parsing Backend Data
- 12.3 DrySister Viewing Girls App (Version 1) – 3. Image Loading Optimization (Writing an Image Cache Framework)
- 12.4 DrySister Viewing Girls App (Version 1) – 4. Adding Data Caching (Introducing SQLite)
- 12.5 DrySister Viewing Girls App (Version 1) – 5. Code Review, Adjustment, and Logging Class Writing
- 12.6 DrySister Viewing Girls App (Version 1) – 6. Icon Creation, Obfuscation, Signing and Packaging, APK Thinning, App Release