Easy Tutorial
❮ Javascript Promise Object Python Extends Init ❯

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():

  1. Adds the view for the given position to the container, creating and displaying it.
  2. 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">

    &lt;android.support.v4.view.ViewPager
        android:id="@+id/vpager_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        &lt;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" />

    &lt;android.support.v4.view.ViewPager
        android:id="@+id/vpager_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        &lt;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" />

&lt;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

ViewPagerDemo.zip


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 Android Basic Tutorial

-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.3 Button and ImageButton

-2.3.4 ImageView (Image View)

-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)

-2.3.6 ToggleButton and Switch

-2.3.7 ProgressBar (Progress Bar)

-2.3.8 SeekBar (Drag 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.4 Adapter Basics

-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.7 Basic Usage of Toast

-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.2 Menu (Menu)

-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)

-3.8 Gestures (Gestures)

-4.1.1 Introduction to Activity

-4.1.2 Intermediate Activity

-4.1.3 Advanced Activity

-4.2.1 Introduction to Service

-4.2.2 Intermediate Service

-4.2.3 Advanced Service

-4.3.1 Introduction to BroadcastReceiver

-4.3.2 In-Depth BroadcastReceiver

Follow on WeChat

❮ Javascript Promise Object Python Extends Init ❯