简单介绍
ViewPager
是属于android.support.v4.view.ViewPager
中的组件,使用的时候全类名引用即可,其中的每一个的内容,需要我们自己创建布局文件,它有专用的适配器来绑定数据和视图,即就是PagerAdapter
,它属于android.support.v4.view.PagerAdapter
。
布局文件
主布局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
item布局文件 tab1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="tab 1 ->"
android:gravity="center"
android:textSize="30dp"/>
</LinearLayout>
tab2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="tab 2 ->"
android:gravity="center"
android:textSize="30dp"/>
</LinearLayout>
使用
- 创建布局加载器,用于将布局文件转换成View
LayoutInflater inflater = LayoutInflater.from(this);
- 加载布局文件,转换成view
View item_tab1=inflater.inflate(R.layout.tab1,null);
View item_tab2=inflater.inflate(R.layout.tab2,null);
- 将view放进List 中
List<View> viewList = new ArrayList<>();
viewList.add(item_tab1);
viewList.add(item_tab2);
- 创建适配器,重写其中的方法
PagerAdapter pagerAdapter = new PagerAdapter(){
@Override
public int getCount() {
return viewList.size(); //返回viewList中view的个数
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
//必须重写一下两个方法,将创建的试图加载创建
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = viewList.get(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = viewList.get(position);
container.removeView(view);
}
}
- 给viewPager设置适配器
viewPager.setAdapter(pagerAdapter);
当然也可以通过
button
支持点击事件,利用viewPager
的方法setCurrentItem()
来显示当前的页面。