关闭

android之自动轮播的ViewPager

标签: 自动轮播的ViewPager
149人阅读 评论(0) 收藏 举报
分类:

Android之自动轮播的ViewPager

1、前言

看到其他APP的自动轮播的ViewPager时,感觉效果挺炫酷的,所以今天自己动手一试,效果挺好,为此记录一番。同时记录下来给广大码农,欢迎大家的批评指正,有不足之处还请留言。

2、说明

我在项目中用到了butterknife框架,一个很实用的框架,我们不用再手动的findViewById,不用手动的添加控件的点击事件,在android studio里面可以一键生成,极大缩减了我们的代码量,再也不用做这种搬砖的事啦。在此,我推荐一篇博客,有意要学习的可以去看看:butterknife的使用,若是使用该框架,只需在module的build.gradle的dependencies节点下添加如下:
compile 'com.jakewharton:butterknife:7.0.1'

3、实现

相关的代码的说明我写在了代码的注释中,若有不懂的,可以留言

1.Mainactivity

package com.example.minhuawang.loopviewpager;
import android.os.Bundle;
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.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Handler;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.viewpager)
    ViewPager viewpager;
    @Bind(R.id.tv_desc)
    TextView tvDesc;
    @Bind(R.id.ll_point)
    LinearLayout llPoint;
    private int[] images;
    private List<ImageView> imageViewList;
    private String[] desc;
    private android.os.Handler handler = new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewpager.setCurrentItem(viewpager.getCurrentItem()+1);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initUI();

        initData();

        initAdapter();

        autoRoll();
    }

    /**
     * 自动滚动
     */
    private void autoRoll() {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                //发消息更新UI
                Message msg = Message.obtain();
                handler.sendMessage(msg);
            }
        };
        timer.scheduleAtFixedRate(task,2000,4000);
    }

    private void initUI() {
       viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
           @Override
           public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
               //滚动是调用
           }
           @Override
           public void onPageSelected(int position) {
               int newPosition = position%imageViewList.size();
               //新的条目选中是调用
               for (int i = 0;i<desc.length;i++){
                   llPoint.getChildAt(i).setEnabled(false);
               }
               llPoint.getChildAt(newPosition).setEnabled(true);
               tvDesc.setText(desc[newPosition]);
           }
           @Override
           public void onPageScrollStateChanged(int state) {
               //滚动状态发生改变的时候
           }
       });
    }

    private void initAdapter() {
        llPoint.getChildAt(0).setEnabled(true);
        tvDesc.setText(desc[0]);
        viewpager.setAdapter(new MyAdapter());

        //保证向右滑动
        viewpager.setCurrentItem(1025);
    }

    private void initData() {
        desc = new String[]{"狂拽炫酷吊炸天", "狂拽炫酷吊炸天","狂拽炫酷吊炸天","狂拽炫酷吊炸天","狂拽炫酷吊炸天"};
        imageViewList = new ArrayList<ImageView>();
        images = new int[]{R.mipmap.a,R.mipmap.b,R.mipmap.c,R.mipmap.d,R.mipmap.e};
        ImageView image;
        View point;
        for(int i = 0;i< images.length;i++){
            image = new ImageView(this);
            image.setBackgroundResource(images[i]);
            imageViewList.add(image);
            //添加小白点,指示器
            point = new View(this);
            point.setEnabled(false);
            point.setBackgroundResource(R.drawable.selector_bg_point);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10,10);
            params.leftMargin = 14;
            llPoint.addView(point,params);

        }
    }

    private class MyAdapter extends PagerAdapter{


        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        //当滑到新的条目,有返回,是否可以复用
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        //返回要显示的内容
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // container 当前的viewPager
            //把View对象添加到容器中
            int newPosition = position % imageViewList.size();//循环公式
            ImageView image = imageViewList.get(newPosition);
            container.addView(image);
            //把view 对象返回给框架,适配器
            return image;//必须重写,否则报错
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);//固定写法
        }
    }
}

2.布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.minhuawang.loopviewpager.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="160dp">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </android.support.v4.view.ViewPager>

        <LinearLayout
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:background="#33000000"
            android:orientation="vertical"
            android:padding="5dp"
            android:layout_height="40dp">
            <TextView
                android:id="@+id/tv_desc"
                android:layout_width="match_parent"
                android:gravity="center_horizontal"
                android:layout_height="wrap_content"
                android:maxLines="1"
                android:textColor="@android:color/white"/>

            <LinearLayout
                android:id="@+id/ll_point"
                android:orientation="horizontal"
                android:gravity="center_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">



            </LinearLayout>

        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

3.相关资源文件

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

<item android:state_enabled="true" android:drawable="@drawable/shape_bg_point_enable"/>

    <item android:state_enabled="false" android:drawable="@drawable/shape_bg_point_disable"/>
</selector>
shape_bg_point_enable.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <corners android:radius="8dp"/>
    <solid android:color="#FFFFFF"/>


</shape>

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

    <corners android:radius="8dp"/>
    <solid android:color="@android:color/darker_gray"/>


</shape>




1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:19696次
    • 积分:682
    • 等级:
    • 排名:千里之外
    • 原创:49篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类