使用ViewPager实现广告自动轮播的效果

package com.loaderman.viewpgerlunbodemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * support v4 和 v7
 * v4: 支持Android api4以上版本
 * <p>
 * v7中包含v4
 */
public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private final int[] mImageIds = new int[]{R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e};
    // 图片标题集合
    private final String[] mImageDes = {"巩俐不低俗,我就不能低俗", "朴树又回来啦!再唱经典老歌引万人大合唱", "揭秘北京电影如何升级", "乐视网TV版大派送", "热血屌丝的反杀"};
    private TextView tvTitle;
    private LinearLayout llContainer;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //切换到下一个页面
            int currentItem = mViewPager.getCurrentItem();
            mViewPager.setCurrentItem(++currentItem);
            //继续发送消息, 形成类似递归的循环
            mHandler.sendEmptyMessageDelayed(0, 3000);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        llContainer = (LinearLayout) findViewById(R.id.ll_container);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(new MyAdapter());
        //设置当前条目位置
        //mViewPager.setCurrentItem(Integer.MAX_VALUE / 2);
        mViewPager.setCurrentItem(mImageIds.length * 100000);
        //添加页面切换的事件监听
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int
                    positionOffsetPixels) {
                //页面滑动监听
            }
            @Override
            public void onPageSelected(int position) {
                //页面选中监听
                position = position % mImageIds.length;
                //更新标题
                tvTitle.setText(mImageDes[position]);
                //切换红点图片
                //将所有点先初始化为灰点
                for (int i = 0; i < mImageIds.length; i++) {
                    ImageView point = (ImageView) llContainer.getChildAt(i);
                    if (i != position) {
                        point.setImageResource(R.drawable.shape_gray);
                    } else {
                        point.setImageResource(R.drawable.shape_red);
                    }
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {
                //页面状态发生变化
            }
        });
        //手动初始化第一个页面的标题
        tvTitle.setText(mImageDes[0]);
        //根据新闻个数, 初始化小圆点
        for (int i = 0; i < mImageIds.length; i++) {
            ImageView point = new ImageView(this);
            //设置margin
            //当前控件的父控件是谁, 就使用谁的布局参数
            //初始化布局参数, 宽高包裹内容
            //一般来讲, 布局文件中控件的属性如果是layout_xxxx, 都需要通过布局参数来设置
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
                   .LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            //从第二个点开始设置左边距
            if (i > 0) {
                params.leftMargin = 10;
                point.setImageResource(R.drawable.shape_gray);
            } else {
                point.setImageResource(R.drawable.shape_red);
            }
            //设置布局参数
            point.setLayoutParams(params);
            //将小圆点添加到线性布局上
            llContainer.addView(point);
        }
        mHandler.sendEmptyMessageDelayed(0, 3000);
        //给ViewPager设置触摸监听
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //停止轮播
                        //可以清除handler中的所有消息
                        mHandler.removeCallbacksAndMessages(null);
                        break;
                    case MotionEvent.ACTION_UP:
                        //继续轮播
                        mHandler.sendEmptyMessageDelayed(0, 3000);
                        break;
                    default:
                        break;
                }
                return false;//返回false表示不消费此事件, 允许viewpager底层处理触摸事件
            }
        });
    }
    class MyAdapter extends PagerAdapter {
        //返回条目个数
        @Override
        public int getCount() {
            // return mImageIds.length;
            return Integer.MAX_VALUE;//条目个数返回整数最大值
        }
        //判断显示的view是不是就是返回的object对象
        //只有是true, 才显示, 否则不显示
        //一般永远这样写了
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
        //初始化条目布局对象, 类似getView
        //ViewPager: 如何避免内存溢出? 永远只最多加载3个页面对象, 当前页, 上一页, 下一页
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //初始化条目布局
            ImageView view = new ImageView(MainActivity.this);
            //0,1,2,3,4
            //5,6,7,8,9-->0,1,2,3,4
            //10->0  11->1
            //15->0
            //当前位置对集合大小取余, 返回0-4的位置信息
            position = position % mImageIds.length;
            final int tempPosition= position;
            //view.setImageResource(mImageIds[position]);
            view.setBackgroundResource(mImageIds[position]);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "点击了"+tempPosition, Toast.LENGTH_SHORT).show();
                }
            });
            //将条目布局添加给ViewPager容器
            container.addView(view);
            System.out.println("初始化条目:" + position);
            //返回布局对象
            return view;
        }
        //销毁布局对象
        //一般永远这样写了
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //super.destroyItem(container, position, object);
            //从容器中移除布局对象
            container.removeView((View) object);
            System.out.println("销毁条目:" + position);
        }
    }
}

 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="180dp">
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="180dp"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#a000"
            android:orientation="vertical"
            android:padding="5dp">
            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="标题"
                android:textColor="#fff"
                android:textSize="16sp"/>
            <LinearLayout
                android:id="@+id/ll_container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:orientation="horizontal">
            </LinearLayout>
        </LinearLayout>
    </FrameLayout>
</LinearLayout>

 页签的圆形的图形绘制:

shape_gray.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
    <solid android:color="#ccc"/>
    <size
        android:width="10dp"
        android:height="10dp"/>
</shape>

 shape_red.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">

    <solid android:color="#f00"/>

    <size
        android:width="10dp"
        android:height="10dp"/>
</shape>

 效果图:

posted on 2017-03-10 14:45  LoaderMan  阅读(209)  评论(0编辑  收藏  举报

导航