一起学Android之ViewPager

本文以一个简单的小例子,简述在Android开发中ViewPager的常见用法,仅供学习分享使用。

概述

ViewPager是一个支持使用者左右滑动的布局管理控件,可以通过一个实现的(适配器)PageAdapter来进行数据和页面的传递。ViewPager更多时候会和Fragment一起使用,方便管理各个页面的生命周期。

涉及知识点

  • ViewPager并非是原生的UI控件,所以使用的时候需要包含全部的包名(android.support.v4.view.ViewPager)。
  • PagerAdapter 是一个抽象基类,开发时需要实现类中的抽象方法。用于将数据在ViewPager中展示出来。
  • PagerAdapter的抽象方法需要实现以下几个:
    • getCount() 用于获取需要展示的子视图的数量
    • isViewFromObject(View view, Object object) 子视图是否需要重新加载,如果已经加载过,则不需要重新加载。
    • destroyItem(ViewGroup container, int position, Object object) 删除子视图
    • instantiateItem(ViewGroup container, int position) 生成对应位置的子视图
  • addOnPageChangeListener 对ViewPager增加监听事件
  • SimpleOnPageChangeListener 是实现OnPageChangeListener接口的类,需要实现onPageSelected(int position)方法即可。
  • ImageView 图片视图,用于显示图片,本例中主要用于ViewPager中的指示器。
  • FragmentPagerAdapter 用于显示Fragment的适配器。
  • FragmentManager 一个用于管理Fragmetn的抽象类,是FragmentPagerAdapter构造函数中的一个参数。

示例截图

图片轮播如下所示:

示例源码

xml布局代码

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     tools:context="com.hex.demoviewpager.MainActivity">
 8     <android.support.v4.view.ViewPager
 9         android:id="@+id/vp_info"
10         android:scrollIndicators="bottom"
11         android:layout_width="match_parent"
12         android:layout_height="match_parent">
13     </android.support.v4.view.ViewPager>
14     <TextView
15         android:id="@+id/tv_title"
16         android:layout_alignBottom="@id/vp_info"
17         android:layout_centerHorizontal="true"
18         android:textSize="20dp"
19         android:text="aaaa"
20         android:layout_marginBottom="30dp"
21         android:layout_width="wrap_content"
22         android:layout_height="wrap_content"/>
23     <LinearLayout
24         android:id="@+id/ll_Indicator"
25         android:layout_alignBottom="@id/vp_info"
26         android:layout_centerHorizontal="true"
27         android:gravity="center"
28         android:orientation="horizontal"
29         android:layout_width="200dp"
30         android:layout_height="wrap_content">
31 
32     </LinearLayout>
33     <Button
34         android:id="@+id/bn_go"
35         android:text="@string/go"
36         android:layout_alignParentTop="true"
37         android:layout_width="wrap_content"
38         android:layout_height="wrap_content"/>
39 </RelativeLayout>
View Code

Java代码(图片轮播)

  1 package com.hex.demoviewpager;
  2 
  3 import android.content.Intent;
  4 import android.support.v4.view.PagerAdapter;
  5 import android.support.v4.view.ViewPager;
  6 import android.support.v7.app.ActionBar;
  7 import android.support.v7.app.AppCompatActivity;
  8 import android.os.Bundle;
  9 import android.util.Log;
 10 import android.view.View;
 11 import android.view.ViewGroup;
 12 import android.widget.Button;
 13 import android.widget.ImageView;
 14 import android.widget.LinearLayout;
 15 import android.widget.TextView;
 16 
 17 public class MainActivity extends AppCompatActivity {
 18 
 19     private ViewPager mViewPager;
 20     int[] imgs;
 21     String[] titles;
 22     TextView tvTitle;
 23     LinearLayout llIndicator;
 24     Button mGo;
 25     @Override
 26     protected void onCreate(Bundle savedInstanceState) {
 27         super.onCreate(savedInstanceState);
 28         setContentView(R.layout.activity_main);
 29         mViewPager= (ViewPager) this.findViewById(R.id.vp_info);
 30         imgs=new int[]{R.drawable.s01,R.drawable.s02,R.drawable.s03,R.drawable.s04,R.drawable.s05};
 31         titles=new String[]{"第一张图","第二张图","第三张图","第四张图","第五张图"};
 32         tvTitle= (TextView) this.findViewById(R.id.tv_title);
 33         //构造适配器并赋值
 34         MyAdapter adapter=new MyAdapter();
 35         mViewPager.setAdapter(adapter);
 36         //初始化第一个标题
 37         tvTitle.setText(titles[0]);
 38         //初始化指示器
 39         llIndicator = (LinearLayout) this.findViewById(R.id.ll_Indicator);
 40         setIndicator(0);
 41         //设置页面切换监听事件
 42         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
 43             /**
 44              * 页面被选中
 45              * @param position
 46              */
 47             @Override
 48             public void onPageSelected(int position) {
 49                 Log.v("DemoViewPager","当前是:"+titles[position]);
 50                 tvTitle.setText(titles[position]);
 51                 //设置指示器
 52                 llIndicator.removeAllViews();
 53                 setIndicator(position);
 54             }
 55         });
 56         //页面跳转
 57         mGo= (Button) this.findViewById(R.id.bn_go);
 58         mGo.setOnClickListener(new View.OnClickListener() {
 59             @Override
 60             public void onClick(View v) {
 61                 Intent intent=new Intent(MainActivity.this,Main2Activity.class);
 62                 startActivity(intent);
 63             }
 64         });
 65     }
 66 
 67     /**
 68      * 设置指示器
 69      * @param position
 70      */
 71     private  void setIndicator(int position){
 72         for(int i=0;i<imgs.length;i++) {
 73             ImageView imgIndicatior = new ImageView(MainActivity.this);
 74             LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, 10);
 75             layoutParams.leftMargin = 10;
 76             layoutParams.rightMargin = 10;
 77             imgIndicatior.setLayoutParams(layoutParams);
 78             if (i == position) {
 79                 imgIndicatior.setImageResource(R.drawable.dot1);
 80             } else {
 81                 imgIndicatior.setImageResource(R.drawable.dot0);
 82             }
 83             llIndicator.addView(imgIndicatior);
 84         }
 85     }
 86 
 87     /*
 88     描述:自定义一适配器
 89      */
 90     class MyAdapter extends PagerAdapter
 91     {
 92 
 93         @Override
 94         public int getCount() {
 95             return imgs == null ? 0 : imgs.length;
 96         }
 97 
 98         /**
 99          * 是否需要重新加载子视图
100          * @param view
101          * @param object
102          * @return
103          */
104         @Override
105         public boolean isViewFromObject(View view, Object object) {
106             return view == object;
107         }
108 
109         @Override
110         public void destroyItem(ViewGroup container, int position, Object object) {
111             //container.removeViewAt(position);
112             container.removeView((View)object);
113         }
114 
115         /**
116          * 生成子视图
117          * @param container
118          * @param position
119          * @return
120          */
121         @Override
122         public Object instantiateItem(ViewGroup container, int position) {
123             ImageView img=new ImageView(container.getContext());
124             img.setImageResource(imgs[position]);
125             container.addView(img);
126             return  img;
127         }
128 
129         @Override
130         public CharSequence getPageTitle(int position) {
131             return titles[position];
132         }
133     }
134 }
View Code

Java代码(Fragment滑动)

 1 package com.hex.demoviewpager;
 2 
 3 import android.support.v4.app.Fragment;
 4 import android.support.v4.app.FragmentActivity;
 5 import android.support.v4.app.FragmentManager;
 6 import android.support.v4.app.FragmentPagerAdapter;
 7 import android.support.v4.view.ViewPager;
 8 import android.support.v7.app.AppCompatActivity;
 9 import android.os.Bundle;
10 import android.util.Log;
11 import android.widget.ImageView;
12 import android.widget.LinearLayout;
13 
14 import java.util.ArrayList;
15 import java.util.List;
16 
17 public class Main2Activity extends FragmentActivity {
18 
19     private ViewPager mViewPager2;
20     private   List<Fragment> mList;
21     LinearLayout llIndicator2;
22     @Override
23     protected void onCreate(Bundle savedInstanceState) {
24         super.onCreate(savedInstanceState);
25         setContentView(R.layout.activity_main2);
26         mViewPager2= (ViewPager) this.findViewById(R.id.vp_info2);
27         mList=new ArrayList<Fragment>();
28         for(int i=0;i<5;i++){
29             ContentFragment fragment=ContentFragment.newInstance("第 "+i+" 个Fragment");
30             mList.add(fragment);
31         }
32         FragmentManager manager = getSupportFragmentManager();
33         MyAdapter2 adapter2=new MyAdapter2(manager);
34         mViewPager2.setAdapter(adapter2);
35         //初始化指示器
36         llIndicator2 = (LinearLayout) this.findViewById(R.id.ll_Indicator2);
37         setIndicator(0);
38         //设置页面切换监听事件
39         mViewPager2.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
40             /**
41              * 页面被选中
42              * @param position
43              */
44             @Override
45             public void onPageSelected(int position) {
46                 //设置指示器
47                 llIndicator2.removeAllViews();
48                 setIndicator(position);
49             }
50         });
51     }
52 
53     /**
54      * 设置指示器
55      * @param position
56      */
57     private  void setIndicator(int position){
58         for(int i=0;i<mList.size();i++) {
59             ImageView imgIndicatior = new ImageView(Main2Activity.this);
60             LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, 10);
61             layoutParams.leftMargin = 10;
62             layoutParams.rightMargin = 10;
63             imgIndicatior.setLayoutParams(layoutParams);
64             if (i == position) {
65                 imgIndicatior.setImageResource(R.drawable.dot1);
66             } else {
67                 imgIndicatior.setImageResource(R.drawable.dot0);
68             }
69             llIndicator2.addView(imgIndicatior);
70         }
71     }
72 
73     /**
74      * 结合Fragement的适配器
75      */
76     class MyAdapter2 extends FragmentPagerAdapter{
77 
78         public MyAdapter2(FragmentManager fm) {
79             super(fm);
80 
81         }
82 
83         @Override
84         public int getCount() {
85             return mList==null ? 0:mList.size();
86         }
87 
88         @Override
89         public Fragment getItem(int position) {
90             return mList.get(position);
91         }
92     }
93 }
View Code

备注

ViewPager支持的Fragment也是android.support.v4.app包中的Fragment,需要调用的Activity也是需要继承android.support.v4.app.FragmentActivity 。ViewPager中的图片指示器是用LinearLayout中图片实现的。

posted @ 2019-01-27 22:44  老码识途呀  阅读(466)  评论(0编辑  收藏  举报