Android基础控件之ViewPager的使用

1、简单一点理解,ViewPager就是我们经常能看到的“轮播”控件;
2、ViewPager的使用分为两个部分:视图和适配器,类似iOS中的View和DataSource;
3、比如我们新建3个xml文件,里面什么都没有,只是背景色不同:红、绿、蓝;
4、ViewPager相对应的适配器叫PagerAdaper,创建一个PagerAdaper的子类;
5、PagerAdaper是一个抽象类,实现4个方法getCount()、isViewFromObject()、instantiateItem()、destroyItem();
6、事件监听则通过addOnPageChangeListener()来实现,类似iOS中的Delegate;
7、关键代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.yusian.viewpager;
 
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private ArrayList<View> viewArray;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        viewPager = (ViewPager)findViewById(R.id.vp_main);
        // 数据
        viewArray = new ArrayList();
        viewArray.add(LayoutInflater.from(this).inflate(R.layout.viewpage_one, null));
        viewArray.add(LayoutInflater.from(this).inflate(R.layout.viewpage_two, null));
        viewArray.add(LayoutInflater.from(this).inflate(R.layout.viewpage_thr, null));
        // 数据源方法
        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return viewArray.size();
            }
 
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
 
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = viewArray.get(position);
                container.addView(view);
                return view;
            }
 
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewArray.get(position));
            }
 
        });
        // 设置监听方法
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                System.out.println(position + "---" + positionOffset + "---" + positionOffsetPixels);
            }
 
            @Override
            public void onPageSelected(int position) {
                System.out.println(position);
            }
 
            @Override
            public void onPageScrollStateChanged(int state) {
                System.out.println("--->"+state);
            }
        });
    }
}

Leave a Reply