android 使用viewpager实现图片轮播效果

第一步:创建xml布局,如下图所示;





    

    
    

第二步:创建drawable,选中和非选中的小圆点

a, 非选中样式的圆点



    
    

b, 选中样式的圆点



    
    

第三步:创建ViewPagerAdapter适配器

package com.example.myapplication_10;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.example.myapplication_10.R;

public class MyPagerAdapter extends PagerAdapter {
    private int[] banners = new int[]{R.mipmap.img_1, R.mipmap.img_2, R.mipmap.img_3};
    private Context context;
    private View.OnClickListener onBannerClickListener;
    private static final String TAG = "MyPagerAdapter";

    public MyPagerAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        //返回int的最大值 可以一直滑动
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Log.e(TAG, "instantiateItem1: " + position);
        position %= banners.length;
        Log.e(TAG, "instantiateItem2: " + position);
        ImageView imageView = new ImageView(context);
        //设置图片缩放类型
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        //把当前的下标通过setTag方法设置进去
        imageView.setTag(position);
        imageView.setImageResource(banners[position]);
        imageView.setOnClickListener(onClickListener);
        container.addView(imageView);
        return imageView;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBannerClickListener.onClick(v);
        }
    };

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    public void setOnBannerClickListener(View.OnClickListener onBannerClickListener) {
        this.onBannerClickListener = onBannerClickListener;
    }

    public int[] getBanners() {
        return banners;
    }
}

第四步:MainActivity函数代码如下;

package com.example.myapplication_10;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private MyPagerAdapter myPagerAdapter;
    private ViewPager viewPager;
    private LinearLayout viewGroup;

    private int currentItem = 0;
    private final Handler handler = new Handler();
    private static final int CAROUSEL_TIME = 3000;




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


        viewPager = findViewById(R.id.viewPager);
        viewGroup = findViewById(R.id.viewGroup);
        myPagerAdapter = new MyPagerAdapter(this);
        myPagerAdapter.setOnBannerClickListener(onBannerClickListener);
        //设置缓存页数
        viewPager.setOffscreenPageLimit(myPagerAdapter.getBanners().length - 1);
        viewPager.setAdapter(myPagerAdapter);
        //添加页面更改监听器
        viewPager.addOnPageChangeListener(onPageChangeListener);

        //将点点的图添加到视图ViewGroup中
        for (int i = 0; i < myPagerAdapter.getBanners().length; i++) {
            ImageView imageView = new ImageView(this);
            //设置图片的宽高 为10像素
            imageView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
            if (i == 0) {
                //第一个为默认选中状态
                imageView.setImageResource(R.drawable.icon_page_select);
            } else {
                imageView.setImageResource(R.drawable.icon_page_normal);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
            viewGroup.addView(imageView, params);
        }
        //给ViewPager设置当前页,这样刚打开软件也能向左滑动
        currentItem = myPagerAdapter.getBanners().length * 50;
        viewPager.setCurrentItem(currentItem);
        handler.postDelayed(mTicker, CAROUSEL_TIME);
    }

    private final Runnable mTicker = new Runnable() {
        @Override
        public void run() {
            long now = SystemClock.uptimeMillis();
            Log.d(TAG, "now:" + now);
//            long next = now + (CAROUSEL_TIME - now % CAROUSEL_TIME);
            //等同于
            long next = now + CAROUSEL_TIME;
            Log.d(TAG, "next: " + next);
            //回调应该运行的绝对时间 3秒后发送消息
            handler.postAtTime(mTicker, next);
            currentItem++;
            viewPager.setCurrentItem(currentItem);
        }
    };

    private View.OnClickListener onBannerClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            Toast.makeText(MainActivity.this, "当前点击位置:" + position, Toast.LENGTH_SHORT).show();
        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        /**
         * function: 当前页面滚动的时候回调这个方法
         * @param position 当前页面的位置
         * @param positionOffset 滑动页面的百分比
         * @param positionOffsetPixels 滑动的像素数
         * @return
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        /**
         * function: 当页面被选中时,会回调这个方法
         * @param position 被选中的页面的位置
         * @return
         */
        @Override
        public void onPageSelected(int position) {
            Log.e(TAG, "onPageSelected: MainActivity" + position);
            currentItem = position;
            //当新页面选中时调用此方法,position 为新选中页面的位置索引
            //在所选页面的时候,点点图片也要发生变化
            setImageBackground(position %= myPagerAdapter.getBanners().length);
            Log.e(TAG, "onPageSelected: " + myPagerAdapter.getBanners().length);
        }

        /**
         * function: 当页面滚动状态变化时,会回调这个方法
         * 有三种状态:静止、滑动、拖拽(这里区别滑动和拖拽,以手指是否接触页面为准)
         * @param state 当前状态
         * @return
         */
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    /**
     * 改变点点点的切换效果
     *
     * @param selectItem 当前选中的页面索引
     */
    private void setImageBackground(int selectItem) {
        for (int i = 0; i < myPagerAdapter.getBanners().length; i++) {
            ImageView imageView = (ImageView) viewGroup.getChildAt(i);
            imageView.setBackground(null);
            if (i == selectItem) {
                imageView.setImageResource(R.drawable.icon_page_select);
            } else {
                imageView.setImageResource(R.drawable.icon_page_normal);
            }
        }
    }

}

以上是总结了网络上资源,效果图如下;

android 使用viewpager实现图片轮播效果_第1张图片

 

你可能感兴趣的:(android学习,android)