android 列表中播放视频(仿搜狐视频、微视等视频播放)

本文介绍了一种在RecyclerView中实现视频自动播放的方法。当列表滑动时,暂停正在播放的视频;停止滑动后,根据可见区域大小判断播放哪个视频。采用MediaPlayer结合TextureView播放,并通过LayoutManager确定播放位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



最近项目中需要是实现在列表中自动播放视频,中间遇到了些问题,终于解决,特来跟大家分享一下:

列表使用的RecyclerView 播放视频使用MediaPlayer+TextureView。

主要思路:

1、监听RecyclerView的滑动,开始滑动时停止正在播放的item。

2、通过LinearLayoutManager 获取当前显示的第一个item及最后一个item

3、RecyclerView停止滑动后,选择item进行播放。如果当前界面只有一个item,播放当前。如果item数量大于2个,播放第二个。如当前界面有两个item则判定哪一个显示的区域比较大。播放item并记录当前position。

附上主要实现逻辑:

try {
			int fristPos = layoutManager.findFirstVisibleItemPosition();
			int lastPos = layoutManager.findLastVisibleItemPosition();
			ViewHolder holder = null;
			if (recyclerView.getChildCount() == 2) {
				View fristView = recyclerView.getChildAt(0);
				if (fristView != null) {
					int[] location = new int[2];
					fristView.getLocationInWindow(location);
					if (location[1] > 0) {
						holder = (ViewHolder) recyclerView.findViewHolderForPosition(fristPos);
						lastPlayPosition = fristPos;
					}
				}
				if (holder == null) {
					View lastView = recyclerView.getChildAt(1);
					if (lastView != null) {
						int[] lastViewLocation = new int[2];
						lastView.getLocationInWindow(lastViewLocation);
						if ((lastViewLocation[1] + videoHeight) < screenHeight) {
							holder = (ViewHolder) recyclerView.findViewHolderForPosition(lastPos);
							lastPlayPosition = lastPos;
						}
					}


				}
			} else if (recyclerView.getChildCount() == 1) {
				holder = (ViewHolder) recyclerView.findViewHolderForPosition(fristPos);
				lastPlayPosition = fristPos;
			} else {
				holder = (ViewHolder) recyclerView.findViewHolderForPosition(fristPos + 1);
				lastPlayPosition = fristPos + 1;
			}


			if (holder != null) {
				holder.play();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值