ViewPager使用
XML布局文件中添加ViewPager控件
1 2 3 4 5 6 |
<android.support.v4.view.ViewPager android:id="@+id/fragment_facility_viewpager" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" />; |
ViewPager需要的适配器
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 |
public class FacilityViewPageAdapt extends PagerAdapter { // ViewPager绑定的View private ArrayList<View> listViews; public FacilityViewPageAdapt(ArrayList<View> listViews) { this.listViews = listViews; } // 获取总的页数 @Override public int getCount() { return listViews.size(); } // 来判断显示的是否是同一个View,这里我们将两个参数相比较返回即可 @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } // 如果滑动的View超出了缓存的范围,就会调用这个方法,将View销毁 @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(listViews.get(position)); } // 当要显示的View可以进行缓存的时候,会调用这个方法进行显示图片的初始化, @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(listViews.get(position)); return listViews.get(position); } } |
Java代码中对ViewPager进行操作
1 2 3 4 5 6 7 8 9 10 11 12 |
viewPager = (ViewPager) mRootView .findViewById(R.id.fragment_facility_viewpager); listViews = new ArrayList<View>(); pageOne = inflater.inflate( R.layout.search_facility_class_viewpage_item, null); pageTwo = inflater.inflate( R.layout.search_facility_class_viewpage_item, null); listViews.add(pageOne); listViews.add(pageTwo); // 设置适配器,将要显示的布局传递过去 viewPager.setAdapter(new FacilityViewPageAdapt(listViews)); |
0 Comments