ViewPager 实现前后自由的“无限”轮播

来源:互联网 发布:物流信息软件 编辑:程序博客网 时间:2024/05/17 00:12

ViewPager 来实现广告条的无限轮播效果。为ViewPager设置适配器以及滑动监听等就可以实现我们想要的功能了。

1、重写viewPager适配器:新建一个类MyAdapter来继承PagerAdapter并重写它的getCountt(),isViewFromObject(View arg0, Object arg1),destroyItem(ViewGroup container, int position, Object object),instantiateItem(ViewGroup container, int position)等方法。2、viewPager设置setOnPageChangeListener()监听。3、中间插入法。

效果图如下:


XML布局如下:

<RelativeLayout 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"    tools:context="${relativePackage}.${activityClass}" >    <FrameLayout        android:layout_width="wrap_content"        android:layout_height="200dp" >        <android.support.v4.view.ViewPager            android:id="@+id/vp_main"            android:layout_width="match_parent"            android:layout_height="match_parent" />        <LinearLayout            android:layout_width="match_parent"            android:layout_height="35dp"            android:layout_gravity="bottom"            android:background="#33000000"            android:gravity="center"            android:orientation="vertical" >            <TextView                android:id="@+id/tv_main"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="图片标题" />            <LinearLayout                android:layout_width="wrap_content"                android:layout_height="wrap_content" >                <View                    android:id="@+id/r_main_1"                    android:layout_width="5dp"                    android:layout_height="5dp"                    android:layout_marginLeft="2dp"                    android:layout_marginRight="2dp"                    android:layout_marginTop="3dp"                    android:background="@drawable/dot_focused" />                <View                    android:id="@+id/r_main_2"                    android:layout_width="5dp"                    android:layout_height="5dp"                    android:layout_marginLeft="2dp"                    android:layout_marginRight="2dp"                    android:layout_marginTop="3dp"                    android:background="@drawable/dot_normal" />                <View                    android:id="@+id/r_main_3"                    android:layout_width="5dp"                    android:layout_height="5dp"                    android:layout_marginLeft="2dp"                    android:layout_marginRight="2dp"                    android:layout_marginTop="3dp"                    android:background="@drawable/dot_normal" />                <View                    android:id="@+id/r_main_4"                    android:layout_width="5dp"                    android:layout_height="5dp"                    android:layout_marginLeft="2dp"                    android:layout_marginRight="2dp"                    android:layout_marginTop="3dp"                    android:background="@drawable/dot_normal" />                <View                    android:id="@+id/r_main_5"                    android:layout_width="5dp"                    android:layout_height="5dp"                    android:layout_marginLeft="2dp"                    android:layout_marginRight="2dp"                    android:layout_marginTop="3dp"                    android:background="@drawable/dot_normal" />            </LinearLayout>        </LinearLayout>    </FrameLayout></RelativeLayout>
主Activity类MainActivity如下:

package com.example.android_viewpagerdemo;import java.util.ArrayList;import java.util.List;import android.R.color;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.os.Handler;import android.support.v4.view.PagerAdapter;import android.support.v4.view.ViewPager;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.MotionEvent;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;/** *  * @author yehu * @time 2016年1月15日下午11:40:56 */public class MainActivity extends Activity {private ViewPager vp;private TextView title;private int[] imageIds;private String[] titles;private List<ImageView> images;private List<View> dots;private int oldposition = 0;private int max;private int currenitem;private boolean flag = false;private Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {currenitem = vp.getCurrentItem();currenitem = (currenitem + 1) % max;vp.setCurrentItem(currenitem);handler.removeMessages(msg.what);handler.sendEmptyMessageDelayed(0, 2000);};};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 获取需要操作的UI组件vp = (ViewPager) findViewById(R.id.vp_main);title = (TextView) findViewById(R.id.tv_main);// 图片的ID数组imageIds = new int[] { R.drawable.a, R.drawable.b, R.drawable.c,R.drawable.d, R.drawable.e };// 图片的集合images = new ArrayList<ImageView>();for (int i = 0; i < imageIds.length; i++) {ImageView image = new ImageView(this);image.setBackgroundResource(imageIds[i]);images.add(image);}max = 20 * images.size();// 图片对应的标题titles = new String[] { "巩俐不低俗,我就不能低俗", "扑树又回来啦!再唱经典老歌引万人大合唱","揭秘北京电影如何升级", "乐视网TV版大派送", "热血屌丝的反杀" };dots = new ArrayList<View>();dots.add(findViewById(R.id.r_main_1));dots.add(findViewById(R.id.r_main_2));dots.add(findViewById(R.id.r_main_3));dots.add(findViewById(R.id.r_main_4));dots.add(findViewById(R.id.r_main_5));title.setTextColor(Color.WHITE);MyAdapter adapter = new MyAdapter(this, images, max);vp.setAdapter(adapter);vp.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {return false;}});vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {int temp = position % images.size();title.setText(titles[temp]);dots.get(oldposition).setBackgroundResource(R.drawable.dot_normal);dots.get(temp).setBackgroundResource(R.drawable.dot_focused);oldposition = temp;}/** * 当Page的滑动状态发生改变时调用 *  * @see ViewPager#SCROLL_STATE_IDLE : 停止没有滑动 * @see ViewPager#SCROLL_STATE_DRAGGING : 开始拖动(只调用一次) * @see ViewPager#SCROLL_STATE_SETTLING: 沉降: *      当手指离开是Pager自动回到当前页或进下/上一页 */@Overridepublic void onPageScrollStateChanged(int state) {// 开始拖动滑动就移除消息if (state == ViewPager.SCROLL_STATE_DRAGGING) {handler.removeMessages(0);vp.setTag(true);} else if (state == ViewPager.SCROLL_STATE_SETTLING) {// 是否拖动过Boolean isDrag = (Boolean) vp.getTag();if (isDrag != null && isDrag) {vp.setTag(false);handler.sendEmptyMessageDelayed(0, 3000);}}}});handler.sendEmptyMessageDelayed(0, 2000);// 设置加载中间部分int item = max / 2 - (max / 2) % images.size();// 22 ->11-->10// 11-11%5=11-1= 10Log.i("TAG", "max= " + max + ",item " + item);vp.setCurrentItem(item);}@Overrideprotected void onDestroy() {super.onDestroy();handler.removeCallbacksAndMessages(null);}}

在本类中设置了ViewPager的滑动监听和适配器。

ViewPager的适配器MyAdapter如下:

package com.example.android_viewpagerdemo;import java.util.List;import android.content.Context;import android.support.v4.view.PagerAdapter;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;/** *  * @author yehu * @time 2016年1月15日下午11:41:04 */public class MyAdapter extends PagerAdapter {private Context context;private List<ImageView> images;private int max;public MyAdapter() {}public MyAdapter(Context context, List<ImageView> images, int max) {this.context = context;this.images = images;this.max = max;}// 数量@Overridepublic int getCount() {return max;}// 判断是否是同一个对象@Overridepublic boolean isViewFromObject(View arg0, Object arg1) {return arg0 == arg1;}// 删除页@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {// super.destroyItem(container, position, object);container.removeView((View) object);}// 加载页@Overridepublic Object instantiateItem(ViewGroup container, int position) {ImageView imageView = images.get(position % images.size());container.addView(imageView);return imageView;}}

其它的布局和资源见本Demo项目如下:

待上传……



0 0
原创粉丝点击