下一篇:
ViewPager需要用到适配器PagerAAdapter,以下四个函数需要重写:
instantiateItem(ViewGroup container, int position):创建指定位置的页面视图。适配器增加即将创建的View视图到这里给定的container中。
destroyItem(ViewGroup container, int position, Object object):移除一个给定位置的页面。getCount():返回当前有效视图的个数。isViewFromObject(View view, Object object):判断instantiateItem(ViewGroup, int)函数所返回来的Key与一个页面视图是否是代表的同一个视图。
主界面的布局只要加上
<android.support.v4.view.ViewPager />
即可:
activity_main.xml:
16 7 12 13
决定ViewPager有3个页面,每个页面都要写布局:
以第一个first_page.xml为例:
1 25 11 12
MainActivity需要在onCreate里对其初始化,并调用适配器:
1 package com.example.hopecapital.myapplication; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.support.v4.view.ViewPager; 6 import android.view.LayoutInflater; 7 import android.view.View; 8 9 import java.util.ArrayList;10 import java.util.List;11 12 13 public class MainActivity extends Activity {14 private View first,second,third;15 private ViewPager viewPager;//对应控件16 private List viewList;//View数组17 18 @Override19 protected void onCreate(Bundle savedInstanceState) {20 super.onCreate(savedInstanceState);21 setContentView(R.layout.activity_main);22 23 /*初始化*/24 viewPager = (ViewPager)findViewById(R.id.viewpager);25 LayoutInflater inflater = getLayoutInflater();26 first = inflater.inflate(R.layout.first_page,null);27 second = inflater.inflate(R.layout.second_page,null);28 third = inflater.inflate(R.layout.third_page,null);29 30 viewList = new ArrayList ();// 将要分页显示的View装入数组中31 viewList.add(first);32 viewList.add(second);33 viewList.add(third);34 35 /*适配器部分*/36 NewPagerAdapter pagerAdapter = new NewPagerAdapter(viewList);37 viewPager.setAdapter(pagerAdapter);38 }39 40 }
最后也是最重要的,继承自PagerAdapter的适配器:
NewPagerAdapter.java:
1 package com.example.hopecapital.myapplication; 2 3 import android.support.v4.view.PagerAdapter; 4 import android.view.View; 5 import android.view.ViewGroup; 6 7 import java.util.List; 8 9 /**10 * Created by LT on 2015/7/27.11 */12 public class NewPagerAdapter extends PagerAdapter{13 public ListviewList;14 15 public NewPagerAdapter(List viewList){16 this.viewList = viewList;17 }18 19 /*下面四个函数是一定要重写的*/20 @Override21 public boolean isViewFromObject(View arg0,Object arg1){22 //判断instantiateItem(ViewGroup, int)函数所返回来的Key与一个页面视图是否是代表的同一个视图(判断key)23 // TODO Auto-generated method stub24 return arg0 == arg1;25 }26 27 @Override28 public int getCount() { //返回要滑动的VIew的个数29 // TODO Auto-generated method stub30 return viewList.size();31 }32 33 @Override34 public void destroyItem(ViewGroup container, int position,35 Object object) { //从当前container中删除指定位置(position)的View;36 // TODO Auto-generated method stub37 container.removeView(viewList.get(position));38 }39 40 @Override41 public Object instantiateItem(ViewGroup container, int position) {42 //实例化:将当前视图添加到container中,并返回当前View(传送key)43 // TODO Auto-generated method stub44 container.addView(viewList.get(position));45 46 return viewList.get(position);47 }48 }
以上,便完成了简单的ViewPager。