Android——ViewPage视频与图片轮滚

一、源码

  • 依赖
implementation 'com.danikula:videocache:2.7.1'
implementation ("com.github.bumptech.glide:glide:4.9.0") {
    exclude group: "com.android.support"
}
  • PZHelp_ViewPager
public class PZHelp_ViewPager extends ViewPager {
    public PZHelp_ViewPager(@NonNull Context context) {
        super(context);
        setPageTransformer(0.5f);
    }

    public PZHelp_ViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setPageTransformer(0.5f);
    }

    public void setPageTransformer(final float pageclip) {
        super.setPageTransformer(false, new PageTransformer() {
            @Override
            public void transformPage(@NonNull View page, float position) {
                if (page.getClass().getSimpleName().equals("LinearLayout")) {
                    View view = ((LinearLayout) page).getChildAt(0);
                    if (position < -pageclip || position > pageclip) {
                        view.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
                    } else {
                        if (position < 0) {//[-1,0]
                            view.setLayoutParams(new LinearLayout.LayoutParams((int) (page.getWidth() * (1 + position / pageclip)), page.getHeight()));
                        } else {//[0,1]
                            view.setLayoutParams(new LinearLayout.LayoutParams((int) (page.getWidth() * (1 - position / pageclip)), page.getHeight()));
                        }
                    }
                }
            }
        }, LAYER_TYPE_NONE);
    }
}
  • PZHelp_ViewPagerAdapter
public class PZHelp_ViewPagerAdapter extends PagerAdapter {
    private static final String TAG = "PZHelp_ViewPagerAdapter";

    private Handler handler = new Handler();

    private List<String[]> respaths = null;

    private View             currentView   = null;
    private VideoView        lastVideoView = null;
    private PZHelp_ViewPager viewPager     = null;

    private int TYPE_IMAGE = 1;
    private int TYPE_VIDEO = 2;

    private int oldposition = -1;

    public PZHelp_ViewPagerAdapter(PZHelp_ViewPager viewPager) {
        this.viewPager = viewPager;
    }

    @Override
    public int getCount() {
        if (respaths != null) {
            return Integer.MAX_VALUE;
        }
        return 0;
    }

    @SuppressLint("ClickableViewAccessibility")
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        int realPosition = position % respaths.size();

        if (getResType(respaths.get(realPosition)[0]) == TYPE_IMAGE) {
            //是图片
            ImageView imageView = new ImageView(container.getContext());
            Glide.with(container.getContext())
                    .load(respaths.get(realPosition)[0])
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(imageView);
            container.addView(imageView);
            return imageView;
        } else if (getResType(respaths.get(realPosition)[0]) == TYPE_VIDEO) {
            //是视频
            VideoView videoView = new VideoView(container.getContext());
            videoView.setVideoPath(getProxy(container.getContext()).getProxyUrl(respaths.get(realPosition)[0]));
            videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
                }
            });
            videoView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

            //套一层LinearLayout用来居中VideoView
            LinearLayout linearLayout = new LinearLayout(container.getContext());
            linearLayout.setBackgroundColor(Color.BLACK);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            linearLayout.setLayoutParams(layoutParams);
            linearLayout.setGravity(Gravity.CENTER);
            linearLayout.addView(videoView);

            container.addView(linearLayout);
            return linearLayout;
        }
        return null;
    }

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        int realPosition = position % respaths.size();

        if (realPosition != oldposition) {//页面切换了
            oldposition = realPosition;

            //获取当前View
            if (object.getClass().getSimpleName().equals("LinearLayout")) {
                currentView = ((LinearLayout) object).getChildAt(0);
            } else {
                currentView = (View) object;
            }

            //暂停上一个视频
            if (lastVideoView != null && lastVideoView.isPlaying()) {
                lastVideoView.pause();
            }

            //判断VideoView
            if (currentView.getClass().getSimpleName().equals("VideoView")) {//当前页为视频界面,当前页视频播放
                handler.removeCallbacks(loopRunnable);
                VideoView videoView = (VideoView) currentView;
                videoView.setVisibility(View.VISIBLE);
                videoView.start();
                lastVideoView = videoView;
            } else if (currentView.getClass().getSimpleName().equals("ImageView")) {//当前页为图片界面
                handler.postDelayed(loopRunnable, Integer.parseInt(respaths.get(realPosition)[1]));
            }
        }
        super.setPrimaryItem(container, position, object);
    }


    private Runnable loopRunnable = new Runnable() {
        @Override
        public void run() {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
        }
    };

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

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

    private int getResType(String respath) {
        if (respath.contains(".jpg") || respath.contains(".png") || respath.contains(".JPG") || respath.contains(".PNG")) {
            return TYPE_IMAGE;
        }
        if (respath.contains(".mp4") || respath.contains(".MP4")) {
            return TYPE_VIDEO;
        }
        return -1;
    }

    public void setData(List<String[]> respaths) {
        this.respaths = respaths;
    }

    public View getCurrentView() {
        return currentView;
    }
}

二、使用

  • 数据为 List<String[]>,每一个String[] 为一个资源链接和播放时间(时间参数仅对图片有效)
private List<String[]> respaths  = new ArrayList<>();
//String[] s1 = {"http://XXXXXXXXX/006.mp4", ""};
//String[] s2 = {"http://XXXXXXXXX/33.png", "5000"};
  • 直接初始化即可使用,对于动态数据源,自行添加使用 viewPagerAdapter.notifyDataSetChanged() 即可
viewPagerAdapter = new PZHelp_ViewPagerAdapter(viewPager);
viewPagerAdapter.setData(respaths);
viewPager.setAdapter(viewPagerAdapter);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值