android的viewpager视频图片轮播实现

项目中有类似功能,所以先写个demo ,待优化布局性能,亲测可行!,CSDN不能发录像,懒得麻烦就不贴视频了——后面项目中用的是网易提供的播放器并把player放在对象里面在创建view时绑定,极好的解决了播放问题,另外seekbar的进度放在线程更新不好,参照网易用Handler出来更好!

public class TestActivity extends AppCompatActivity {

    TextView mNumTV;
    ViewPager mViewPager;
    VpAdapter mAdapter;
    List<View> mViewList = new ArrayList<>();
    List<BannerBean> mItemList = new ArrayList<>();
    OnPagerItemClickListener mOnItemClickListener;

    int mCurrentItem = 0;
    boolean isShowVideo = false;
    boolean isThread = false;
    MediaPlayer mediaPlayer;
    BannerBean mPlayVideoBean;
    View mView;
    SurfaceView mVideoSV;
    ImageView mSwitchIV;
    SeekBar mMiniSB;
    TextView mTotalMiniTV;

    private int WHAT_AUTO_PLAY = 1000;
    private boolean isAutoPlay = true;
    private int autoPlayDuration = 4000;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == WHAT_AUTO_PLAY) {
                if (mViewPager != null) {
                    if (isAutoPlay) {
                        mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
                    }
                    handler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, autoPlayDuration);
                }
            }
            return false;
        }
    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        initView();
        initData();
        initEvent();

    }


    private void initView() {
        mViewPager = findViewById(R.id.vp_activity_test);
        mNumTV = findViewById(R.id.tv_activity_test_num);
    }

    private void initData() {
        for (int i = 0; i < 6; i++) {
            BannerBean bannerBean = new BannerBean();
            bannerBean.setId("" + i);
            if (i % 2 > 0) {
                bannerBean.setType(BannerBean.TYPE_PIC);
                bannerBean.setBeanImage("https://c-ssl.duitang.com/uploads/item/201910/31/20191031112329_rqtcw.thumb.300_300_c.jpg");
            } else {
                bannerBean.setType(BannerBean.TYPE_VIDEO);
                bannerBean.setBeanImage("http://1252492711.vod2.myqcloud.com/958d2b29vodtransgzp1252492711/0b9adbaf5285890781624263761/v.f19999.mp4");
            }
            mItemList.add(bannerBean);
        }


        for (int i = 0; i < mItemList.size(); i++) {
            mViewList.add(getView(i));
        }

        mAdapter = new VpAdapter(mViewList,true) {
            @Override
            public int getItemPosition(@NonNull Object object) {
                //重新getItemPosition,使得notifyDataSetChanged有效
                return PagerAdapter.POSITION_NONE;
            }
        };
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(mItemList.size());

        mViewPager.setCurrentItem(0);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mNumTV.setText(getString(R.string.num_total, 1, mItemList.size()));
        startAutoPlay();
    }

    private void initEvent() {
        mOnItemClickListener = new OnPagerItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {

                Toast.makeText(TestActivity.this, "点击了", Toast.LENGTH_LONG).show();
                BannerBean bean = mItemList.get(position % mItemList.size());
                mView = null;
                mView = view;
                mSwitchIV = view.findViewById(R.id.iv_item_banner_video_switch);
                mTotalMiniTV = view.findViewById(R.id.tv_item_banner_video_progress_total);
                try {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()
                            && mPlayVideoBean != null && mPlayVideoBean.getId().equals(bean.getId())) {
                        mediaPlayer.pause();
                        mSwitchIV.setVisibility(VISIBLE);
                        mSwitchIV.setImageResource(R.drawable.ic_new_player_pause);
                    } else if (mediaPlayer != null
                            && !mediaPlayer.isPlaying()
                            && mPlayVideoBean != null && mPlayVideoBean.getId().equals(bean.getId())) {
                        mediaPlayer.start();
                        mSwitchIV.setVisibility(GONE);
                        mSwitchIV.setImageResource(R.drawable.ice_playing);
                    } else if (mediaPlayer != null) {
                        startMediaPlayer(bean, view);
                    }
                    if (mediaPlayer != null) {
                        mTotalMiniTV.setText(mediaPlayer.getDuration());
                    }
                    mPlayVideoBean = bean;
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("TAG", e.toString());
                }

            }

            @Override
            public void onItemTouch(int position, View view) {
                mView = null;
                mView = view;
                mSwitchIV = view.findViewById(R.id.iv_item_banner_video_switch);
                isShowVideo = !isShowVideo;
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mSwitchIV.setImageResource(R.drawable.ice_playing);
                } else {
                    mSwitchIV.setImageResource(R.drawable.ic_new_player_pause);
                }
                if (isShowVideo) {
                    mSwitchIV.setVisibility(GONE);
                } else {
                    mSwitchIV.setVisibility(VISIBLE);
                }
            }

            @Override
            public void onItemChange(int position, int progress, View view) {
                BannerBean bean = mItemList.get(position % mItemList.size());
                mVideoSV = view.findViewById(R.id.vv_item_banner_video);
                mSwitchIV = view.findViewById(R.id.iv_item_banner_video_switch);
                mMiniSB = view.findViewById(R.id.sb_item_banner_video_progress);
                mTotalMiniTV = view.findViewById(R.id.tv_item_banner_video_progress_total);
                if (mediaPlayer != null) {
                    try {
                        mediaPlayer.reset();
                        // 设置播放的视频源
                        mediaPlayer.setDataSource(bean.getBeanImage());
                        // 设置显示视频的SurfaceHolder
                        mediaPlayer.setDisplay(mVideoSV.getHolder());
                        mediaPlayer.prepare();
                        mediaPlayer.seekTo(progress);
                        mediaPlayer.start();
                        mPlayVideoBean = bean;

                        mSwitchIV.setVisibility(GONE);
                        mSwitchIV.setImageResource(R.drawable.ice_playing);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            }
        };

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mCurrentItem=position % mItemList.size();
                final BannerBean bean = mItemList.get(position % mItemList.size());
                switch (bean.getType()) {
                    case BannerBean.TYPE_VIDEO:
                        Log.e("TAG", "视频类型" + position % mItemList.size());
                        if (mediaPlayer != null) {
                            View view = mViewList.get(position % mItemList.size());
                            if (mediaPlayer.isPlaying() && mPlayVideoBean != null
                                    && mPlayVideoBean.getId().equals(bean.getId())) {
                                startMediaPlayer(bean, view);
                            }
                        }
                        isAutoPlay = false;
                        break;

                    case BannerBean.TYPE_PIC:
                        if (mediaPlayer != null && mView != null) {
                            mediaPlayer.pause();
                            mSwitchIV = mView.findViewById(R.id.iv_item_banner_video_switch);
                            mSwitchIV.setVisibility(VISIBLE);
                            mSwitchIV.setImageResource(R.drawable.ic_new_player_pause);
                        }
                        isAutoPlay = true;
                        break;
                }

                mNumTV.setText(getString(R.string.num_total, position % mItemList.size() + 1, mItemList.size()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    /**
     * 开始自动轮播
     */
    private void startAutoPlay() {
        stopAutoPlay(); // 避免重复消息
        if (isAutoPlay) {
            handler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, autoPlayDuration);
        }
    }

    /**
     * 停止自动轮播
     */
    private void stopAutoPlay() {
        if (isAutoPlay) {
            handler.removeMessages(WHAT_AUTO_PLAY);
        }
    }

    private View getView(final int position) {
        final BannerBean bean = mItemList.get(position);
        switch (bean.getType()) {
            case BannerBean.TYPE_PIC:
                RoundedImageView imageView = new RoundedImageView(this);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setCornerRadius(0);
                imageView.mutateBackground(true);
                imageView.setTileModeX(Shader.TileMode.REPEAT);
                imageView.setTileModeY(Shader.TileMode.REPEAT);

                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });


                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(this).load(bean.getBeanImage()).into(imageView);
                return imageView;

            case BannerBean.TYPE_VIDEO:
                final View view = LayoutInflater.from(this).inflate(R.layout.item_banner_video, null);
                final SurfaceView mVideo = view.findViewById(R.id.vv_item_banner_video);
                final RoundedImageView mRoundedImageView = view.findViewById(R.id.iv_item_banner_video);
                final ImageView mSwitch = view.findViewById(R.id.iv_item_banner_video_switch);
                final SeekBar mMini = view.findViewById(R.id.sb_item_banner_video_progress);
                final TextView mTotalMini = view.findViewById(R.id.tv_item_banner_video_progress_total);
                mRoundedImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                mRoundedImageView.setCornerRadius(0);
                mRoundedImageView.mutateBackground(true);
                mRoundedImageView.setTileModeX(Shader.TileMode.REPEAT);
                mRoundedImageView.setTileModeY(Shader.TileMode.REPEAT);
                mRoundedImageView.setVisibility(GONE);
                mTotalMini.setText("00:00");

                mVideo.getHolder().addCallback(new SurfaceHolder.Callback() {
                    @Override
                    public void surfaceCreated(SurfaceHolder holder) {
//                            currentPosition = mediaPlayer.getCurrentPosition();
//                            mediaPlayer.stop();
                        // 设置播放的视频源
//                            try {
//                                MediaPlayer player=new MediaPlayer();
//                                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//                                player.setDataSource(bean.getBeanImage());
//                                // 设置显示视频的SurfaceHolder
//                                player.setDisplay(mVideo.getHolder());
//                                mMini.setMax(player.getDuration());
//                                mMini.setProgress(player.getCurrentPosition());
//                                player=null;
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
                        Canvas canvas = holder.lockCanvas();
                        Bitmap bitmap = ImageUtil.drawableToBitmap(ContextCompat.getDrawable(TestActivity.this, R.drawable.ic_default));
                        if (canvas != null) {
                            synchronized (bitmap) {
                                canvas.drawBitmap(bitmap, 0, 0, null);
                                holder.unlockCanvasAndPost(canvas);
                            }
                        }
                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    }

                    @Override
                    public void surfaceDestroyed(SurfaceHolder holder) {

                    }
                });

                mSwitch.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mOnItemClickListener != null) {
                            mOnItemClickListener.onItemClick(position, view);
                        }
                    }
                });

                mMini.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        int progress = seekBar.getProgress();
                        if (mOnItemClickListener != null && mediaPlayer != null && mediaPlayer.isPlaying()) {
                            mOnItemClickListener.onItemChange(position, progress, view);
                        } else {
                            seekBar.setProgress(0);
                        }
                    }
                });

                view.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (mOnItemClickListener != null) {
                            mOnItemClickListener.onItemTouch(position, view);
                        }
                        return false;
                    }
                });

                mRoundedImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(this).load(bean.getBeanImage() + "?vframe/jpg/offset/1").into(mRoundedImageView);
                return view;
        }

        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryMediaPlayer();
    }


    //启动线程的一个方法
    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (mMiniSB.getProgress() <= mMiniSB.getMax() && mediaPlayer != null) {
                //获取音乐当前播放的位置
                int position = mediaPlayer.getCurrentPosition();
                mMiniSB.setProgress(position);
            }
        }
    }

    private void startMediaPlayer(BannerBean bean, View view) {
        mView = null;
        mView = view;
        mVideoSV = view.findViewById(R.id.vv_item_banner_video);
        mSwitchIV = view.findViewById(R.id.iv_item_banner_video_switch);
        try {
            if (mediaPlayer != null && mPlayVideoBean != null
                    && mPlayVideoBean.getId().equals(bean.getId())) {
                mediaPlayer.start();
                mSwitchIV.setVisibility(GONE);
                mSwitchIV.setImageResource(R.drawable.ice_playing);
            } else if (mediaPlayer != null) {
                mediaPlayer.reset();
                // 设置播放的视频源
                mediaPlayer.setDataSource(bean.getBeanImage());
                // 设置显示视频的SurfaceHolder
                mediaPlayer.setDisplay(mVideoSV.getHolder());
                mediaPlayer.prepare();
                mediaPlayer.start();
                mPlayVideoBean = bean;


                mMiniSB = view.findViewById(R.id.sb_item_banner_video_progress);
                mTotalMiniTV = view.findViewById(R.id.tv_item_banner_video_progress_total);
                int duration = mediaPlayer.getDuration();
                //将进度条设置最大值为:音乐的总时长
                mMiniSB.setMax(duration);

                TimeUtil timeUtil = new TimeUtil();
                mTotalMiniTV.setText("" + timeUtil.stringForTime(duration));
                //启动线程
                new MyThread().start();
                mSwitchIV.setVisibility(GONE);
                mSwitchIV.setImageResource(R.drawable.ice_playing);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void destoryMediaPlayer() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.setOnCompletionListener(null);
                mediaPlayer.setOnPreparedListener(null);
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        } catch (Exception e) {
        }
    }
}

另外还有OnPagerItemClickListener ,其他的工具类和VpAdapter 就继承的PagerAdapter 没什么内容就不贴了

public interface OnPagerItemClickListener {
    void onItemClick(int position, View view);

    void onItemTouch(int position, View view);

    void onItemChange(int position,int progress, View view);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值