Android viewpager uses

1. Introduction to viewpager

viewpager is a simple page switching component, which can be filled with multiple Views, and then we can slide left and right to switch between different Views. Viewpager mainly creates an adapter to fill it with multiple views, and when sliding left and right, switch between different views to achieve the effect.

2. Description of the main methods

ViewPager directly inherits from ViewGroup, so it is a container class where other view classes can be added.
ViewPager needs a PagerAdapter adapter class to provide data to it.
ViewPager is often used with Fragment, and provides special FragmentPagerAdapter and FragmentStatePagerAdapter classes for ViewPager in Fragment.

1. setAdapter (PagerAdapter adapter)
This method sets the adapter for ViewPager. ViewPager has three adapters, which have different characteristics. I will explain these three adapters below.
2. setCurrentItem(int item)
This method sets the interface for displaying the position of the item.
3. setOffscreenPageLimit(int limit)
This method is used to set the number of cached pages on the left and right sides of the currently displayed page.
4. addOnPageChangeListener (OnPageChangeListener listener) This method adds monitoring for
ViewPager when switching pages

Three methods of OnPageChangeListener:

onPageScrollStateChanged(int state)

The method changes when the finger operates the screen. There are three values: 0(END), 1(PRESS), 2(UP). When you slide the page with your finger, this method will be triggered when the finger is pressed down, and the state value is 1. When the finger is lifted, if there is a slide (even if it is small), this value will become 2, and then finally become 0 . Execute this method three times in total. A special case is that no sliding occurs after the finger is pressed down. At this time, this method will only be called twice, and the state values ​​are 1 and 0 respectively. When setCurrentItem turns the page, this method will be executed twice, and the state values ​​are 2 and 0 respectively.
onPageScrolled(int position, float positionOffset, int positionOffsetPixels)

This method will always be called during the sliding process. The parameters of this method are described as follows:
position: When sliding with a finger, if the finger is pressed on the page and does not move, the position is consistent with the current page index; if the finger is dragged to the left (Flip the corresponding page to the right). At this time, the position is consistent with the current page most of the time. Only when the page is turned successfully will the last call become the target page; if the finger is dragged to the right (the corresponding page is flipped to the left ), at this time the position is consistent with the target page most of the time, and the last call will change to the original page only when the page turning is unsuccessful. When directly setting setCurrentItem to turn the page, if it is adjacent (for example, it is the second page now, jump to the first or third page), if the page is turned to the right, most of the time it is consistent with the current page , only at the end it becomes the target page; if it is turned to the left, the position and the target page are the same. This is basically the same as dragging the page with your finger to turn it. If it is not adjacent, for example, if I jump from the first page to the third page, the position is first 0, then gradually becomes 1, and then gradually becomes 2; I jump from the third page to the first page, The position is 1 first, and then gradually becomes 0, and it does not appear to be 2.
positionOffset: The sliding ratio of the current page. If the page is turned to the right, this value will continue to increase, and finally it will suddenly change to 0 after approaching 1. If the page is flipped to the left, this value keeps getting smaller and finally becomes 0.
positionOffsetPixels : The sliding pixels of the current page, the change is consistent with positionOffset.

onPageSelected(int position)

position is the index of the selected page, this method is called when the page is selected or the page is swiped enough to switch to the page and the finger is lifted.

The relationship between the three:

The execution sequence of the three methods: when you drag the page with your finger, first execute onPageScrollStateChanged(1), and then execute onPageScrolled continuously. When you put your finger, execute onPageScrollStateChanged(2) immediately, then execute onPageSelected immediately, and Then continue to execute onPageScrollStateChanged, and finally execute onPageScrollStateChanged(0).
In short:

onPageScrolled: Called during screen sliding.

onPageSelected: represents which page is selected.

onPageScrollStateChanged: called when the finger operates the screen

Three, viewpager instance

Example 1 of viewpager:

1. Initialize and use in mainActivity.java, as follows:

mainActivity.java file

public ViewPager vp;
ArrayList<View> viewlist;
myPagerAdapter mypageradapter;


vp = findViewById(R.id.viewpager);
viewlist = new ArrayList<>();
LayoutInflater li = getLayoutInflater();
viewlist.add(li.inflate(R.layout.activity1,null,false));
viewlist.add(li.inflate(R.layout.activity2,null,false));
viewlist.add(li.inflate(R.layout.activity3,null,false));
mypageradapter = new myPagerAdapter(viewlist);
vp.setAdapter(mypageradapter);

2. Implementation of myPagerAdapter class

Adapter myPagerAdapter.java file

package com.testviewpager;

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

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

import java.util.ArrayList;

public class myPagerAdapter extends PagerAdapter{
private ArrayList<View> viewlist;
public myPagerAdapter(ArrayList<View> viewList){
viewlist = viewList;
}
@Override
public int getCount() {
return viewlist == null ? 0: viewlist.size();
}

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

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewlist.get(position));
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
}

3. The layout configuration of the main xml file is as follows:

activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

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

</androidx.viewpager.widget.ViewPager>

</androidx.constraintlayout.widget.ConstraintLayout>

4. Implementation of each activity xml

activity1.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World, this is first activity!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity2.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World, this is second activity!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity2.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World, this is second activity!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity3.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World, this is third Activity !"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Note:

Four methods that must be rewritten to use PagerAdapter:

getCount(): Get how many views 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 is removed when finishUpdate(viewGroup) returns.

instantiateItem(): ①Add the view at the given position to the ViewGroup (container), create and display it ②Return an Object (key) representing the newly added page, usually just return the view itself directly, of course you can also You can customize your own key, but there must be a one-to-one correspondence between the key and each view

isViewFromObject(): Determine whether the Key returned by the instantiateItem(ViewGroup, int position) function and a page view represent the same view (that is, whether they correspond to each other and represent the same View), usually we directly write return view == object!

Example two:

slide with title

PagerTabStrip: underlined

activity_main.xml

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

</androidx.viewpager.widget.ViewPager>

Adapter file myPagerAdapterSec.java

package com.testviewpager;

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 myPagerAdapterSec extends PagerAdapter{
private ArrayList<View> viewlist;
private ArrayList<String> titleList;
public myPagerAdapterSec(ArrayList<View> viewList, ArrayList<String> titleList){
viewlist = viewList;
this.titleList = titleList;
}
@Override
public int getCount() {
return viewlist == null ? 0: viewlist.size();
}

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

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewlist.get(position));
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}

Main mainActivity.java file

package com.testviewpager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

public ViewPager vp;
ArrayList<View> viewlist;
//myPagerAdapter mypageradapter;
myPagerAdapterSec mypageradaptersec;
ArrayList<String> titleList;

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

vp = findViewById(R.id.viewpager);
viewlist = new ArrayList<>();
LayoutInflater li = getLayoutInflater();
viewlist.add(li.inflate(R.layout.activity1,null,false));
viewlist.add(li.inflate(R.layout.activity2,null,false));
viewlist.add(li.inflate(R.layout.activity3,null,false));
// mypageradapter = new myPagerAdapter(viewlist);
// vp.setAdapter(mypageradapter);
titleList = new ArrayList<>();
titleList.add("第一个");
titleList.add("第二个");
titleList.add("第三个");


mypageradaptersec = new myPagerAdapterSec(viewlist,titleList);
vp.setAdapter(mypageradaptersec);
}
}

Guess you like

Origin blog.csdn.net/qq_33782617/article/details/126912514