android.support.v4.view.ViewPager
ViewPager的使用跟AbsListView,AbsSpinner类似,需要用一个adapter填充数据,同时实现了onPagerChangeListener接口。
ViewPager需要的adapter继承自android.support.v4.view.PageAdapter,getCount返回adapter的长度,destroyItem滑出屏幕做remove操作,instantiateItem返回填充的视图对象。
要想让ViewPager显示循环的效果网上大多采用给adapter的getCount返回一个很长的数字,然后在返回视图对象的时候用长度getCount%真实数据集合的长度去求余数,求的的余数就是数据集合中拿出来要给instantiateitem返回的视图对象。
然后还可以根据这个余数去设置indicator(小圆点索引)的状态
如图:
代码:
初始化一个装这ImageView的List
List<ImageView> mViewPagerBannerList = new ArrayList<ImageView>();
for (int i = 0; i < 7; i++) {ImageView mImageView = (ImageView) LayoutInflater.from(getActivity()).inflate( R.layout.fragment_market_featured_item0_imageview, null);mViewPagerBannerList.add(mImageView);
}
重写PageAdapter
class MyBannerPageAdapter extends PagerAdapter {List<ImageView> mImageViews;public MyBannerPageAdapter(List<ImageView> mImageViews) {this.mImageViews = mImageViews;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn mImageViews.size() * 100;}@Overridepublic boolean isViewFromObject(View arg0, Object arg1) {// TODO Auto-generated method stubreturn arg0 == arg1;}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {// TODO Auto-generated method stubcontainer.removeView(mImageViews.get(position % mImageViews.size()));}@Overridepublic Object instantiateItem(ViewGroup container, final int position) {ImageView mView = mImageViews.get(position % mImageViews.size());ImageLoader loader = new ImageLoader(mQueue,//以下这一部分代码是Vollay动态给加载图片的VolleyBitmapCache.getCache());ImageListener imageListener = ImageLoader.getImageListener(mView,0, 0);loader.get(mBannerApps.get(position % mImageViews.size()).getBanner_link(), imageListener);try {container.addView(mImageViews.get(position % mImageViews.size()), 0);} catch (Exception e) {// handler something}return mImageViews.get(position % mImageViews.size());//根据余数返回要填充的ImageView}RequestQueue mQueue = Volley.newRequestQueue(getActivity());}
如果你的ViewPager位于ListView的头部,你就会发现对内容的单击事件没法监听了,如果监听了ViewPager的onClickListener之后,ViewPager的滑动会受到影响,我的做法是重写ViewPager,重写onTouch事件,在down和up事件上作文章,可见ViewPager嵌套使用的文章:http://blog.csdn.net/u013045971/article/details/41512055
大家有更好的方式的话,可以告诉我一下,谢谢。