Simple use of ViewPager for Android

  • Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

A UI control introduced in Android 3.0 — ViewPager

Function: The View can be switched through gesture sliding, which is generally used to do APP guide page or realize picture rotation. Because it is introduced after 3.0, if you want to use it under the lower version, you need to introduce V4 compatible package

ViewPager is a simple page-switching component. We can fill it with multiple views, and then we can swipe left and right to switch between different views. We can animate our ViewPager with setPageTransformer().

Like the ListView and GridView, we need a Adapter to bind our View to the ViewPager, and the ViewPager has a specific Adapter — The PagerAdapter

1.ViewPager simple toggle

Swipe to toggle views

Operation effect:

  1. Write the activity_main.xml layout

      
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

   <androidx.viewpager.widget.ViewPager
       android:id="@+id/viewpager"
       android:layout_width="match_parent"
       android:layout_height="600dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ViewPagre"
    android:layout_gravity="center"/>
</LinearLayout>
Copy the code
  1. Write three layouts layout1.xml, Layout2.xml, and Layout3.xml

All three layouts are the same, so there’s only one layout.


      
<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:background="#72C43C"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I'm the first page."
        android:textColor="#ff0000"
        android:textSize="30sp"
        android:layout_marginTop="200dp"
        android:layout_gravity="center"/>
</LinearLayout>
Copy the code
  1. Write the MainActivity activity class
package com.mq.viewpager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private List<View> mViews;  // An array of views
    private View view1,view2,view3;
    private PagerAdapter mPagerAdapter;/ / adapter
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager=findViewById(R.id.viewpager);// Instantiate the Viewpager control

        LayoutInflater inflater = getLayoutInflater();// Get the layout object management
        view1=inflater.inflate(R.layout.layout1,null);// Instantiate view
        view2=inflater.inflate(R.layout.layout2,null);
        view3=inflater.inflate(R.layout.layout3,null);

        mViews=new ArrayList<View>();// Store the layout to be displayed in the list array
        mViews.add(view1);
        mViews.add(view2);
        mViews.add(view3);

        // Instantiate the adapter of a PagerAdapter
        mPagerAdapter=new PagerAdapter() {
            @Override   // Returns the number of views to slide
            public int getCount(a) {
                return mViews.size();
            }

            @Override  // To determine whether a View from pager is associated with an object returned by the instantiateItem method
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view==object;
            }

            @Override  // Delete the View in the specified position from the current container;
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(mViews.get(position));
            }

            @NonNull
            @Override  // First: add the current View to the container. Second: Return the current View
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(mViews.get(position));
                returnmViews.get(position); }}; mViewPager.setAdapter(mPagerAdapter);// Set the adapter}}Copy the code

Note:

Four methods must be overridden using PagerAdapter:

GetCount (): Gets how many views there are in the viewPager

DestroyItem (): Removes a page at a given location. It is the adapter’s responsibility to remove this view from the container. This is to ensure that the view can be removed when finishUpdate(viewGroup) returns.

instantiateItem(): Return an Object(key) that represents the new page. Usually, you can return the view itself. Of course, you can also customize your own key, but each view should have a one-to-one relationship with the key

isViewFromObject(): Check whether the Key returned from the instantiateItem(ViewGroup, int Position) function represents the same view as the page view Return View == object!

2. Title bar — PagerTitleStrip and PagerTabStrip

Follow the ViewPager slide to slide the title, these two are provided by the official, one is normal text, one is underlined, and you can click the text to switch pages

PagerTitleStripOperation effect:

  1. The layout files for the three views are the same as in Example 1
  2. Modify the activity_main. XML layout file

      
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

   <TextView
       android:layout_width="match_parent"
       android:layout_height="48dp"
       android:background="#CCFF99"
       android:gravity="center"
       android:text="PagerTitleStrip demo"
       android:textColor="# 000000"
       android:textSize="18sp" />

   <androidx.viewpager.widget.ViewPager
       android:id="@+id/viewpager"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center">

      <androidx.viewpager.widget.PagerTitleStrip
          android:id="@+id/pagertitle"
          android:layout_width="wrap_content"
          android:layout_height="40dp"
          android:layout_gravity="top"
          android:textColor="# 000000" />
   </androidx.viewpager.widget.ViewPager>


</LinearLayout>
Copy the code
  1. Customize a MyPagerAdapter adapter
package com.mq.viewpager;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;

import java.util.ArrayList;

public class MyPagerAdapter extends PagerAdapter {


    private ArrayList<View> mViewlist;
    private ArrayList<String> mtitlelist;

    public MyPagerAdapter(a) {}public MyPagerAdapter(ArrayList<View> viewlist, ArrayList<String> mtitlelist) {
        mViewlist = viewlist;
        this.mtitlelist = mtitlelist;
    }

    @Override
    public int getCount(a) {
        return mViewlist.size();// Return the view array size
    }


    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(mViewlist.get(position));
        return mViewlist.get(position);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(mViewlist.get(position));
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        returnmtitlelist.get(position); }}Copy the code
  1. Write the MainActivity code
package com.mq.viewpager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private ArrayList<View> mViews;  // An array of views
    private View view1,view2,view3;
    private MyPagerAdapter mAdapter;/ / adapter
    private ArrayList<String> mtitle;// An array of titles

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager = findViewById(R.id.viewpager);// Instantiate the Viewpager control

        LayoutInflater inflater = getLayoutInflater();// Get the layout object management
        view1 = inflater.inflate(R.layout.layout1, null);// Instantiate view
        view2 = inflater.inflate(R.layout.layout2, null);
        view3 = inflater.inflate(R.layout.layout3, null);

        mViews = new ArrayList<View>();// Store the layout to be displayed in the list array
        mViews.add(view1);
        mViews.add(view2);
        mViews.add(view3);

        mtitle = new ArrayList<String>();// An array of titles
        mtitle.add("Recommended");
        mtitle.add("Hot");
        mtitle.add("Live");

        mAdapter=new MyPagerAdapter(mViews,mtitle);// Instantiate the adapter
        mViewPager.setAdapter(mAdapter);// Set the adapter}}Copy the code

PagerTabStrip: is the same as PagerTitleStrip with one more underline:

Simply change activity_main. XML’s PagerTitleStrip to PagerTabStrip

These simple usage styles are ugly and often used with other controls in our development.

That’s all for today’s sharing! Epsilon = epsilon = epsilon = epsilon = epsilon = epsilon = ┌ (;  ̄ cardiac  ̄) ┘