简介
ViewPager:用来滑动切换界面,相当于一个容器,里面放着你要切换的layout。
布局文件
在你需要有滑动切换功能的布局文件加入如下代码:
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</android.support.v4.view.ViewPager>
之后,就建立你需要的每一个滑动界面,这个滑动界面很简单,其实就是一个layout文件,比如建立如下几个view:
layout1
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="189dp"
android:text="view1" />
</RelativeLayout >
layout2
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="189dp"
android:text="view2" />
</RelativeLayout >
这里就不赘述了,想要几个,就创建几个就好了。
程序代码
首先,要初始化viewpager和view,也就是把布局文件和对象对应起来。
viewPager = (ViewPager) findViewById(R.id.viewpager);
LayoutInflater inflater=getLayoutInflater();
view1 = inflater.inflate(R.layout.layout1, null);
view2 = inflater.inflate(R.layout.layout2,null);
view3 = inflater.inflate(R.layout.layout3, null);
然后创建一个view数组,用来装这几个view文件
viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
之后,创建一个PageView的适配器
PagerAdapter pagerAdapter = new PagerAdapter() {
@Override
// 这个函数就是用来告诉框架,这个view的id是不是这个object。
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == arg1;
}
@Override
//返回个数
public int getCount() {
// TODO Auto-generated method stub
return viewList.size();
}
@Override
删除指定view
public void destroyItem(ViewGroup container, int position,
Object object) {
// TODO Auto-generated method stub
container.removeView(viewList.get(position));
}
@Override
//将当前视图添加到container中,返回view
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
container.addView(viewList.get(position));
return viewList.get(position);
}
};
适配器的这四个方法需要重写,其功能已在注释处写好,这里不再赘述。
最后一步,把适配器添加到你的viewPager。
viewPager.setAdapter(pagerAdapter);