Android在ViewPager中使用自定义View,而不是Fragment

参考:ViewPager without Fragments

一般来说,系统提供了使用Fragment的Adapter,这样在ViewPager中使用Fragment就比较方便。然而有时候我们需要自定义View,而不是Fragment时,可以参考下面的方式:

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
//我只对Adapter进行介绍和备份,其余的布局等可以看参考文章
/**
* 自定义Adapter,作为ViewPager的adapter
**/
public class CustomPagerAdapter extends PagerAdapter {

private Context mContext;

public CustomPagerAdapter(Context context) {
mContext = context;
}

@Override
public Object instantiateItem(ViewGroup collection, int position) {
//在这个回调方法中加载布局、初始化组件,绑定数据等操作
CustomPagerEnum customPagerEnum = CustomPagerEnum.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(customPagerEnum.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}

@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
//在这个回调方法中,移除指定的view
collection.removeView((View) view);
}

@Override
public int getCount() {
//ViewPager一共有多少页
return CustomPagerEnum.values().length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}

@Override
public CharSequence getPageTitle(int position) {
//获取页面的标题,在TabHost与ViewPager配合使用时,TabHost会使用该回调返回的字符串设置为当前页面的标题
CustomPagerEnum customPagerEnum = CustomPagerEnum.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}

}