【Android 进阶】仿抖音系列之翻页上下滑切换视频(一)

2020-03-15 作者:编程知识要点   |   浏览(198)

前言

大家好,这是这个系列的第四篇,在阅读这篇文章之前,建议可以先看下之前系列的文章,为了节省篇幅,之前详细说过的地方,这里就不再详细描述了:

  • 【Android 进阶】仿抖音系列之翻页上下滑切换视频
  • 【Android 进阶】仿抖音系列之列表播放视频
  • 【Android 进阶】仿抖音系列之列表播放视频
  • 【Android 进阶】仿抖音系列之翻页上下滑切换视频
  • 【Android 进阶】仿抖音系列之视频预览和录制

这一篇,要说实现的是第一篇中的翻页切换视频。

前言

上一篇中,我们实现了仿抖音上下翻页切换视频的效果,这一篇,我们来实现抖音列表播放视频。

  • 【Android 进阶】仿抖音系列之翻页上下滑切换视频
  • 【Android 进阶】仿抖音系列之列表播放视频
  • 【Android 进阶】仿抖音系列之列表播放视频
  • 【Android 进阶】仿抖音系列之翻页上下滑切换视频
  • 【Android 进阶】仿抖音系列之视频预览和录制

之前也在github上找到一个demo,这是链接,原理和我的一样,只是用起来比较麻烦。。。

最近公司在做个短视频的项目,其中借鉴了很多抖音的设计,其中就有抖音的上下滑切换视频。

思路

在第一篇中,我们用的是垂直滑动的ViewPagerFragment 实现,详细过程可以看看第一篇文章。这里,我们用RecyclerViewSnapHelper来实现。

思路

这里用到了RecyclerViewonScrolledonScrollStateChanged 监听,在onScrolled中判断当前可见的position,结合onScrollStateChanged中返回的当前RecyclerView的滑动状态,当是拖动和停止滚动时,可以播放;当是惯性滑动时,暂停播放。

tip: 关于RecyclerView3种滑动状态,RecyclerView.SCROLL_STATE_IDLERecyclerView.SCROLL_STATE_DRAGGINGRecyclerView.SCROLL_STATE_SETTLING,大家可以自行百度,这里不做过多的描述了。

rvList.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); firstVisibleItem = layoutManager.findFirstVisibleItemPosition(); lastVisibleItem = layoutManager.findLastVisibleItemPosition(); } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { switch  { case RecyclerView.SCROLL_STATE_IDLE://停止滚动 /**在这里执行,视频的自动播放与停止*/ autoPlayVideo(recyclerView); break; case RecyclerView.SCROLL_STATE_DRAGGING://拖动 autoPlayVideo(recyclerView); break; case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动 JZVideoPlayer.releaseAllVideos(); break; } } });

布局就是一个RecyclerView,就不贴了,下面是Adapter

 urlList = new ArrayList<>(); urlList.add("http://image.38.hn/public/attachment/201805/100651/201805181532123423.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803151735198462.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803150923220770.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803150922255785.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803150920130302.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803141625005241.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803141624378522.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803131546119319.mp4"); videoAdapter = new ListVideoAdapter; rvList.setLayoutManager(new LinearLayoutManager(ListActivity.this)); rvList.setAdapter(videoAdapter);

Adapter这里自己做了个封装,可以用原生或者其他封装比较好的,这里就不贴了

 class ListVideoAdapter extends BaseRecAdapter<String, VideoViewHolder> { public ListVideoAdapter(List<String> list) { super; } @Override public void onHolder(VideoViewHolder holder, String bean, int position) { holder.mp_video.setUp(bean, JZVideoPlayerStandard.CURRENT_STATE_NORMAL); if (position == 0) { holder.mp_video.startVideo(); } Glide.with.load.into(holder.mp_video.thumbImageView); holder.tv_title.setText("第" + position + "个视频"); } @Override public VideoViewHolder onCreateHolder() { return new VideoViewHolder(getViewByRes(R.layout.item_video)); } } public class VideoViewHolder extends BaseRecViewHolder { public View rootView; public MyVideoPlayer mp_video; public TextView tv_title; public VideoViewHolder(View rootView) { super; this.rootView = rootView; this.mp_video = rootView.findViewById(R.id.mp_video); this.tv_title = rootView.findViewById(R.id.tv_title); } }

item_video.xml 布局如下

<LinearLayout xmlns:andro android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android: android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center" android:textSize="18sp" /> <com.ch.doudemo.widget.MyVideoPlayer android: android:layout_width="match_parent" android:layout_height="500dp" /></LinearLayout>

这里使用的是 JiaoZiVideoPlayer,其中MyVideoPlayer 是之前公司项目需要,对其做的个性化定制,这里下面再说。

下来就是本篇的核心,通过判断可见项,暂停/播放视频,代码如下

/** * 自动播放 */ private void autoPlayVideo(RecyclerView recyclerView) { if (firstVisibleItem == 0 && lastVisibleItem == 0 && recyclerView.getChildAt != null) { MyVideoPlayer videoView = null; if (recyclerView != null && recyclerView.getChildAt != null) { videoView = recyclerView.getChildAt.findViewById(R.id.mp_video); } if (videoView != null) { if (videoView.currentState == JZVideoPlayer.CURRENT_STATE_NORMAL || videoView.currentState == JZVideoPlayer.CURRENT_STATE_PAUSE) { videoView.startVideo(); } } } for (int i = 0; i <= lastVisibleItem; i++) { if (recyclerView == null || recyclerView.getChildAt == null) { return; } MyVideoPlayer videoView = recyclerView.getChildAt.findViewById(R.id.mp_video); if (videoView != null) { Rect rect = new Rect(); //获取视图本身的可见坐标,把值传入到rect对象中 videoView.getLocalVisibleRect; //获取视频的高度 int videoHeight = videoView.getHeight(); if (rect.top <= 100 && rect.bottom >= videoHeight) { if (videoView.currentState == JZVideoPlayer.CURRENT_STATE_NORMAL || videoView.currentState == JZVideoPlayer.CURRENT_STATE_PAUSE) { videoView.startVideo(); } return; } JZVideoPlayer.releaseAllVideos(); } else { JZVideoPlayer.releaseAllVideos(); } } }

顺便说一下,为啥用JiaoZiVideoPlayer,就是因为 JZVideoPlayer.releaseAllVideos();,一句代码就可以暂停所有的播放器,否则自己要实现这个还是比较麻烦的

需要去掉原播放器的进度条、按钮,点击视频,全屏播放,再次点击取消全屏。

我的做法是添加一个透明度为0的布局,覆盖在播放器上,这样实际上点击的是我们添加的布局

tip:这里有个小技巧,可以粘贴源码中的布局,重要的事情说三遍,不要修改文件名、不要修改文件名、不要修改文件名,找到相关布局,设置android:visibility="gone",这样我们的项目中的布局就会替换掉原来的布局。

jz_layout_standard.xml 代码如下

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:andro android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/black" android:descendantFocusability="blocksDescendants"> <FrameLayout android: android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> <ImageView android: android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:background="#000000" android:scaleType="fitCenter" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone"> <LinearLayout android: android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" android:background="@drawable/jz_bottom_bg" android:gravity="center_vertical" android:orientation="horizontal" android:visibility="invisible"> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="14dp" android:text="00:00" android:textColor="#ffffff" /> <SeekBar android: android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1.0" android:background="@null" android:max="100" android:maxHeight="1dp" android:minHeight="1dp" android:paddingBottom="8dp" android:paddingLeft="12dp" android:paddingRight="12dp" android:paddingTop="8dp" android:progressDrawable="@drawable/jz_bottom_seek_progress" android:thumb="@drawable/jz_bottom_seek_thumb" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="00:00" android:textColor="#ffffff" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:clickable="true" android:paddingLeft="20dp" android:text="clarity" android:textAlignment="center" android:textColor="#ffffff" /> <ImageView android: android:layout_width="52.5dp" android:layout_height="fill_parent" android:paddingLeft="14dp" android:paddingRight="14dp" android:scaleType="centerInside" android:src="@drawable/jz_enlarge" /> </LinearLayout> </LinearLayout> <ProgressBar android: style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="1.5dp" android:layout_alignParentBottom="true" android:max="100" android:progressDrawable="@drawable/jz_bottom_progress" /> <ImageView android: android:layout_width="24dp" android:layout_height="24dp" android:layout_marginLeft="6dp" android:layout_marginTop="6dp" android:background="@drawable/jz_click_back_tiny_selector" android:visibility="gone" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:visibility="gone"> <RelativeLayout android: android:layout_width="match_parent" android:layout_height="60dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@drawable/jz_title_bg" android:gravity="center_vertical"> <ImageView android: android:layout_width="23dp" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:paddingLeft="12dp" android:paddingStart="12dp" android:scaleType="centerInside" android:src="@drawable/jz_click_back_selector" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginEnd="12dp" android:layout_marginLeft="12dp" android:layout_marginRight="12dp" android:layout_marginStart="12dp" android:layout_toEndOf="@+id/back" android:layout_toLeftOf="@+id/battery_time_layout" android:layout_toRightOf="@+id/back" android:ellipsize="end" android:maxLines="2" android:textColor="#ffffff" android:textSize="18sp" /> <LinearLayout android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginEnd="14dp" android:layout_marginRight="14dp" android:gravity="center_vertical" android:orientation="vertical"> <ImageView android: android:layout_width="23dp" android:layout_height="10dp" android:layout_gravity="center_horizontal" android:background="@drawable/jz_battery_level_10" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_vertical" android:maxLines="1" android:textColor="#ffffffff" android:textSize="12.0sp" /> </LinearLayout> </RelativeLayout> </LinearLayout> <ProgressBar android: android:layout_width="@dimen/jz_start_button_w_h_normal" android:layout_height="@dimen/jz_start_button_w_h_normal" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:indeterminateDrawable="@drawable/jz_loading" android:visibility="invisible" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:visibility="gone"> <LinearLayout android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_gravity="center_vertical"> <ImageView android: android:layout_width="@dimen/jz_start_button_w_h_normal" android:layout_height="@dimen/jz_start_button_w_h_normal" android:src="@drawable/jz_click_play_selector" /> </LinearLayout> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/start_layout" android:layout_centerHorizontal="true" android:layout_marginTop="6dp" android:text="@string/replay" android:textColor="#ffffff" android:textSize="12sp" android:visibility="invisible" /> <LinearLayout android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:gravity="center_horizontal" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/video_loading_faild" android:textColor="@android:color/white" android:textSize="14sp" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:background="@drawable/retry_bg" android:paddingBottom="4dp" android:paddingLeft="9dp" android:paddingRight="9dp" android:paddingTop="4dp" android:text="@string/click_to_restart" android:textColor="@android:color/white" android:textSize="14sp" /> </LinearLayout> </LinearLayout> <RelativeLayout android: android:layout_width="match_parent" android:layout_height="match_parent" android:alpha="0" android:background="@color/cf0f2f7"></RelativeLayout> <LinearLayout android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:padding="15dp" android:visibility="gone"> <ImageView android: android:layout_width="16dp" android:layout_height="18dp" android:background="@mipmap/stop" /> </LinearLayout></RelativeLayout>

还需要实现循环播放,这个比较简单,重写onAutoCompletion方法,当其播放完成时,继续播放即可。

 @Override public void onAutoCompletion() { thumbImageView.setVisibility(View.GONE); if (currentScreen == SCREEN_WINDOW_FULLSCREEN) { onStateAutoComplete(); setUp getCurrentUrl(), JZVideoPlayer.SCREEN_WINDOW_FULLSCREEN); } else { super.onAutoCompletion(); setUp getCurrentUrl(), JZVideoPlayer.CURRENT_STATE_NORMAL); } //循环播放 startVideo(); }

到这里,列表播放这个功能已经完成了。

  • 【Android 进阶】仿抖音系列之翻页上下滑切换视频
  • 【Android 进阶】仿抖音系列之列表播放视频
  • 【Android 进阶】仿抖音系列之列表播放视频
  • 【Android 进阶】仿抖音系列之翻页上下滑切换视频
  • 【Android 进阶】仿抖音系列之视频预览和录制

问题

什么是 SnapHelper

SnapHelper是一个抽象类,官方提供了一个LinearSnapHelper的子类,可以让RecyclerView滚动停止时相应的Item停留中间位置。在25.1.0版本中,官方又提供了一个PagerSnapHelper的子类,可以使RecyclerViewViewPager一样的效果,一次只能滑一页,而且居中显示。详细源码解读可以看这里让你明明白白的使用RecyclerView——SnapHelper详解,这里我们用到的就是PagerSnapHelper

这里用重写了ViewPageronInterceptTouchEventonTouchEvent方法,使其可以上下滑动切换视图。代码如下:

如何使用

使用非常简单,只需要创建对象之后调用attachToRecyclerView()附着到对应的RecyclerView对象上就可以了。

 snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView;

下来是组装数据,这里还是用之前的视频

 urlList = new ArrayList<>(); urlList.add("http://image.38.hn/public/attachment/201805/100651/201805181532123423.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803151735198462.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803150923220770.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803150922255785.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803150920130302.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803141625005241.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803141624378522.mp4"); urlList.add("http://image.38.hn/public/attachment/201803/100651/201803131546119319.mp4");

设置Adapter

 videoAdapter = new ListVideoAdapter; layoutManager = new LinearLayoutManager(Page2Activity.this, LinearLayoutManager.VERTICAL, false); rvPage2.setLayoutManager(layoutManager); rvPage2.setAdapter(videoAdapter);

Adapter 代码如下,这里和第二篇中使用的Adapter 一致,其中的MyVideoPlayer 是基于 JiaoZiVideoPlayer的自定义的播放,在第二篇【Android 进阶】仿抖音系列之列表播放视频和第三篇【Android 进阶】仿抖音系列之列表播放视频 中已经有详细的描述,这里不再赘述了。

 class ListVideoAdapter extends BaseRecAdapter<String, VideoViewHolder> { public ListVideoAdapter(List<String> list) { super; } @Override public void onHolder(VideoViewHolder holder, String bean, int position) { holder.mp_video.setUp(bean, JZVideoPlayerStandard.CURRENT_STATE_NORMAL); if (position == 0) { holder.mp_video.startVideo(); } Glide.with.load.into(holder.mp_video.thumbImageView); holder.tv_title.setText("第" + position + "个视频"); } @Override public VideoViewHolder onCreateHolder() { return new VideoViewHolder(getViewByRes(R.layout.item_page2)); } } public class VideoViewHolder extends BaseRecViewHolder { public View rootView; public MyVideoPlayer mp_video; public TextView tv_title; public VideoViewHolder(View rootView) { super; this.rootView = rootView; this.mp_video = rootView.findViewById(R.id.mp_video); this.tv_title = rootView.findViewById(R.id.tv_title); } }

item_page2.xml 布局如下

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:andro xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android: android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center" android:textSize="18sp" /> <com.ch.doudemo.widget.MyVideoPlayer android: android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /></android.support.constraint.ConstraintLayout>

需要注意的是,RecyclerView 的默认布局父布局不是充满全屏的,就算我们在布局中设置match_parent也是没用,需要在onHolder中添加如下代码,重新设置

 ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;

到这里,基本功能已经实现,我们需要做的就是当RecyclerView 滑动时,播放当前可见的视频,暂停不可见的视频。这里我们用的还是第二篇提到的onScrollStateChanged 监听。

相比之前,这里的逻辑简单的多了,由于每次只有1个item处于可见状态,我们就只需要在停止滑动时,播放当前可见的视频,暂停其余不可见的视频。

 rvPage2.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { switch  { case RecyclerView.SCROLL_STATE_IDLE://停止滚动 View view = snapHelper.findSnapView(layoutManager); JZVideoPlayer.releaseAllVideos(); RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder; if (viewHolder != null && viewHolder instanceof VideoViewHolder) { ((VideoViewHolder) viewHolder).mp_video.startVideo(); } break; case RecyclerView.SCROLL_STATE_DRAGGING://拖动 break; case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动 break; } } });

这样就差不多大功告成了,最后别忘记在Activity 不可见时,暂停所有视频

 @Override public void onPause() { super.onPause(); JZVideoPlayer.releaseAllVideos(); }
/** * 作者: ch * 时间: 2018/7/30 0030-下午 2:53 * 描述: * 来源: */public class VerticalViewPager extends ViewPager { private boolean isVertical = false; public VerticalViewPager(@NonNull Context context) { super; } public VerticalViewPager(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } private void init() { // The majority of the magic happens here setPageTransformer(true, new HorizontalVerticalPageTransformer; // The easiest way to get rid of the over scroll drawing that happens on the left and right setOverScrollMode(OVER_SCROLL_NEVER); } public boolean isVertical() { return isVertical; } public void setVertical(boolean vertical) { isVertical = vertical; init(); } private class HorizontalVerticalPageTransformer implements PageTransformer { private static final float MIN_SCALE = 0.75f; @Override public void transformPage(View page, float position) { if (isVertical) { if (position < -1) { page.setAlpha; } else if (position <= 1) { page.setAlpha; // Counteract the default slide transition float xPosition = page.getWidth() * -position; page.setTranslationX(xPosition); //set Y position to swipe in from top float yPosition = position * page.getHeight(); page.setTranslationY(yPosition); } else { page.setAlpha; } } else { int pageWidth = page.getWidth(); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. page.setAlpha; } else if (position <= 0) { // [-1,0] // Use the default slide transition when moving to the left page page.setAlpha; page.setTranslationX; page.setScaleX; page.setScaleY; } else if (position <= 1) { // (0,1] // Fade the page out. page.setAlpha(1 - position); // Counteract the default slide transition page.setTranslationX(pageWidth * -position); page.setTranslationY; // Scale the page down (between MIN_SCALE and 1) float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs); page.setScaleX(scaleFactor); page.setScaleY(scaleFactor); } else { // (1,+Infinity] // This page is way off-screen to the right. page.setAlpha; } } } } /** * Swaps the X and Y coordinates of your touch event. */ private MotionEvent swapXY(MotionEvent ev) { float width = getWidth(); float height = getHeight(); float newX =  / height) * width; float newY =  / width) * height; ev.setLocation(newX, newY); return ev; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (isVertical) { boolean intercepted = super.onInterceptTouchEvent(swapXY; swapXY; // return touch coordinates to original reference frame for any child views return intercepted; } else { return super.onInterceptTouchEvent; } } @Override public boolean onTouchEvent(MotionEvent ev) { if (isVertical) { return super.onTouchEvent(swapXY; } else { return super.onTouchEvent; } }}

本文由永利官网发布于编程知识要点,转载请注明出处:【Android 进阶】仿抖音系列之翻页上下滑切换视频(一)

关键词: