VIEwPager介绍
VIEwPager的功能就是可以使视图滑动,就像Lanucher左右滑动那样。
VIEwPager用于实现多页面的切换效果,该类存在于Google的兼容包androID-support-v4.jar里面.
VIEwPager:
1)VIEwPager类直接继承了VIEwGroup类,所有它是一个容器类,可以在其中添加其他的vIEw类。
2)VIEwPager类需要一个PagerAdapter适配器类给它提供数据。
3)VIEwPager经常和Fragment一起使用,并且提供了专门的FragmentPagerAdapter和FragmentStatePagerAdapter类供Fragment中 的VIEwPager使用。
4)在编写VIEwPager的应用的使用,还需要使用两个组件类分别是PagerTitleStrip类和PagerTabStrip类,PagerTitleStrip类直接继承 自VIEwGroup类,而PagerTabStrip类继承PagerTitleStrip类,所以这两个类也是容器类。但是有一点需要注意,在定义XML的layout 的时候,这两个类必须是VIEwPager标签的子标签,不然会出错。
本文将详细介绍关于AndroID VIEwPager中显示图片与播放视频填坑的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一.需求来源与实现思路
1.最近项目需求中有用到需要在VIEwPager中播放视频和显示图片的功能,视频是本地视频,最开始的实现思路是VIEwPager中根据当前item位置对应的是图片还是视频去初始化PhotoVIEw和SurfaceVIEw,同时销毁时根据item的位置去判断移除PhotoVIEw和SurfaceVIEw。
2.上面那种方式确实是可以实现的,但是存在2个问题,第一,MediaPlayer的生命周期不容易控制并且存在内存泄漏问题。第二,连续三个item都是视频时,来回滑动的过程中发现会出现上个视频的最后一帧画面的BUG。
3.未提升用户体验,视频播放器初始化完成前上面会覆盖有该视频的第一帧图片,但是发现存在第一帧图片与视频第一帧信息不符的情况,后面会通过代码给出解决方案。
4.图片和视频尺寸如何适配以保证不变形。
二.需要填的坑
1.对于MediaPlayer的生命周期不容易控制的本质原因是这种实现思路上我的播放器只有1个,频繁的初始化和销毁造成了问题,所以后面我更改了实现方式,一个item的视频对应一个播放器。
2.对于滑动过程中发现会出现上个视频的最后一帧画面的BUG,发现是surfaceVIEw这个控件造成的,后面通过将播放的载体更换为TextureVIEw完美解决该问题。
3.SurfaceVIEw与TextureVIEw的本质异同
第一:两者都能在独立的线程中绘制和渲染,在专用的GPU线程中大大提高渲染的性能。
第二:SurfaceVIEw专门提供了嵌入视图层级的绘制界面,开发者可以控制该界面像Size等的形式,能保证界面在屏幕上的正确位置。但也有局限:
1.由于是独立的一层VIEw,更像是独立的一个Window,不能加上动画、平移、缩放;
2.两个SurfaceVIEw不能相互覆盖。
第三:Texture更像是一般的VIEw,像TextVIEw那样能被缩放、平移,也能加上动画。TextureVIEw只能在开启了硬件加速的Window中使用,并且消费的内存要比SurfaceVIEw多,并伴随着1-3帧的延迟。
第四:屏幕锁屏时SurfaceVIEw会销毁重建,TextureVIEw不会!
三.具体实现核心代码
1.VIEwPager的初始化
mAdapter = ImagebrowseFragmentPagerAdapter(supportFragmentManager,this,imgs) imgs_vIEwpager.offscreenPagelimit = 1 imgs_vIEwpager.adapter = mAdapter imgs_vIEwpager.currentItem = mposition //为了处理首次点击时视频播放的问题 val message = Message.obtain() message.what = START_PLAY_VIDEO mHandler.sendMessageDelayed(message,200)@H_404_78@
2.Handler处理消息
private val START_PLAY_VIDEO = 0private var DELETE_VIDEO = 1private var DELETE_VIDEO_START_PLAY = 2private var mHandler = Handler(Handler.Callback { msg -> when (msg.what) { //开始播放视频 START_PLAY_VIDEO -> Notifydispatch.dispatch(PrevIEwPlayVIDeoEvent(mposition)) //删除视频时刷新ui DELETE_VIDEO -> { mAdapter?.setimgs(imgs) } //解决删除视频时之后跳转到另一个item,当它是视频时不继续播放的问题 DELETE_VIDEO_START_PLAY -> Notifydispatch.dispatch(PrevIEwPlayVIDeoEvent(mDeleteposition)) } true })@H_404_78@
3.删除视频或图片的处理逻辑
private fun deletePhotos(position: Int) { if (imgs!!.isEmpty()) { return } Threaddispatch.right_Now.execute({ var file: file? file = file(imgs.get(position)) if (file != null && file?.exists()!!) { val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_file) val uri = Uri.fromfile(file) intent.data = uri sendbroadcast(intent) file?.delete() imgs.removeAt(position) } if (position == imgs.size) { mDeleteposition = position - 1 } else { mDeleteposition = position } val message = Message.obtain() message.what = DELETE_VIDEO mHandler.sendMessage(message) Notifydispatch.dispatch(DeletePrevIEwPhotoEvent(imgs)) val message1 = Message.obtain() message1.what = DELETE_VIDEO_START_PLAY mHandler.sendMessageDelayed(message1,200) if (imgs.isEmpty()) { finish() } })// } }@H_404_78@
4.VIEwPager对应的Adapter
package com.immomo.camerax.gui.vIEw.adapter;import androID.content.Context;import androID.os.Bundle;import androID.support.v4.app.Fragment;import androID.support.v4.app.FragmentManager;import androID.support.v4.app.FragmentStatePagerAdapter;import androID.support.v4.app.FragmentTransaction;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import com.immomo.camerax.gui.fragment.PrevIEwimgFragment;import com.immomo.camerax.gui.fragment.PrevIEwVIDeoFragment;import java.util.ArrayList;import java.util.List;/** * Created by liuxu on 2018/3/26. */public class ImagebrowseFragmentPagerAdapter extends FragmentStatePagerAdapter { private Context mContext; private List<String> datas; private int mCurrentSelectedposition = -1; private FragmentManager mFragmentManager; private FragmentTransaction mFragmentTransaction; private ArrayList<Fragment> mFragments = new ArrayList<>(); public ImagebrowseFragmentPagerAdapter(FragmentManager fm,Context context,List<String> datas) { super(fm); mFragmentManager = fm; mContext = context; this.datas = datas; } public voID removeContext(){ mContext = null; } @OverrIDe public voID setPrimaryItem(VIEwGroup container,int position,Object object) { mCurrentSelectedposition = position; } @OverrIDe public voID startUpdate(VIEwGroup container) { super.startUpdate(container); } public voID setimgs(List<String> imgs) { this.datas = imgs; notifyDataSetChanged(); } //处理更新无效----删除条目 @OverrIDe public int getItemposition(Object object) { return position_NONE; } public int getPrimaryItemposition() { return mCurrentSelectedposition; } public ImagebrowseFragmentPagerAdapter(FragmentManager fm) { super(fm); } @OverrIDe public boolean isVIEwFromObject(VIEw vIEw,Object object) { return vIEw == ((Fragment) object).getVIEw(); } @OverrIDe public Fragment getItem(int position) { Bundle bundle = new Bundle(); bundle.putString("url",datas.get(position)); bundle.putInt("position",position); if (datas.get(position).endsWith(".jpg")) { PrevIEwimgFragment prevIEwimgFragment = new PrevIEwimgFragment(); prevIEwimgFragment.setArguments(bundle); return prevIEwimgFragment; } else { PrevIEwVIDeoFragment prevIEwVIDeoFragment = new PrevIEwVIDeoFragment(); prevIEwVIDeoFragment.setArguments(bundle); return prevIEwVIDeoFragment; } } @OverrIDe public int getCount() { return datas == null ? 0 : datas.size(); } @OverrIDe public Object instantiateItem(VIEwGroup container,int position) { return super.instantiateItem(container,position); } @OverrIDe public voID destroyItem(VIEwGroup container,Object object) { super.destroyItem(container,position,object); }}@H_404_78@
5显示图片对应的Fragment
package com.immomo.camerax.gui.fragment;import androID.os.Bundle;import androID.support.annotation.Nullable;import androID.support.v4.app.Fragment;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import com.bumptech.glIDe.GlIDe;import com.immomo.camerax.R;import com.immomo.camerax.foundation.util.StatusbarUtils;import com.immomo.camerax.gui.vIEw.ResizablePhotoVIEw;/** * Created by liuxu on 2018/3/27. */public class PrevIEwimgFragment extends Fragment { @Nullable @OverrIDe public VIEw onCreateVIEw(LayoutInflater inflater,@Nullable VIEwGroup container,@Nullable Bundle savedInstanceState) { VIEw vIEw = inflater.inflate(R.layout.fragment_prevIEw_photo,null); ResizablePhotoVIEw resizablePhotoVIEw = vIEw.findVIEwByID(R.ID.customPhotoVIEw); String url = getArguments().getString("url"); GlIDe.with(getContext()).load(url).into(resizablePhotoVIEw); resizablePhotoVIEw.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw vIEw) { getActivity().finish(); } }); return vIEw; } @OverrIDe public voID onPause() { super.onPause(); } @OverrIDe public voID onResume() { super.onResume(); } @OverrIDe public voID onDetach() { super.onDetach(); } @OverrIDe public voID onDestroyVIEw() { super.onDestroyVIEw(); } @OverrIDe public voID onStart() { super.onStart(); } @OverrIDe public voID onDestroy() { super.onDestroy(); } @OverrIDe public voID setUserVisibleHint(boolean isVisibletoUser) { super.setUserVisibleHint(isVisibletoUser); }}@H_404_78@
6.图片根据宽度适配高度的自定义view
package com.immomo.camerax.gui.vIEw;import androID.content.Context;import androID.graphics.drawable.Drawable;import androID.util.AttributeSet;import com.github.chrisbanes.photovIEw.PhotoVIEw;/** * Created by liuxu on 2018/4/7. */public class ResizablePhotoVIEw extends PhotoVIEw { public ResizablePhotoVIEw(Context context) { super(context); } public ResizablePhotoVIEw(Context context,AttributeSet attr) { super(context,attr); } public ResizablePhotoVIEw(Context context,AttributeSet attr,int defStyle) { super(context,attr,defStyle); } @OverrIDe protected voID onMeasure(int wIDthMeasureSpec,int heightmeasureSpec) { Drawable d = getDrawable(); if (d != null){ int wIDth = MeasureSpec.getSize(wIDthMeasureSpec); //高度根据使得图片的宽度充满屏幕计算而得 int height = (int) Math.ceil((float) wIDth * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWIDth()); setMeasuredDimension(wIDth,height); }else { super.onMeasure(wIDthMeasureSpec,heightmeasureSpec); } }}@H_404_78@
7.播放视频对应的Fragment
/** * Created by liuxu on 2018/3/27. */public class PrevIEwVIDeoFragment extends Fragment { private ImageVIEw mPhotoVIEw; private TextureVIEw mTextureVIEw; private String mUrl; private int mposition; private AndroIDMediaPlayer mIjkVodMediaPlayer; private boolean mIsSelected; private boolean mIsFirstPrepared; private PrevIEwPlayVIDeoSubscriber mPrevIEwPlayVIDeoSubscriber = new PrevIEwPlayVIDeoSubscriber() { @OverrIDe public voID onEventMainThread(PrevIEwPlayVIDeoEvent event) { super.onEventMainThread(event); MDLog.e("liuxu",event.getposition()+""); if (event != null && event.getposition() == mposition) { //说明是当前条目 if (mIjkVodMediaPlayer != null && !mIjkVodMediaPlayer.isPlaying()) { if (mTextureVIEw != null) { mIjkVodMediaPlayer.setSurface(mSurface); mIjkVodMediaPlayer.prepareAsync(); mPhotoVIEw.setVisibility(VIEw.VISIBLE); } } mIsSelected = true; } else { if (mIjkVodMediaPlayer != null && mIjkVodMediaPlayer.isPlaying()) { mIjkVodMediaPlayer.pause(); mIjkVodMediaPlayer.stop(); } if (mPhotoVIEw != null) { mPhotoVIEw.setVisibility(VIEw.VISIBLE); } mIsSelected = false; } } }; private String mWIDth; private String mHeight; @Nullable @OverrIDe public VIEw onCreateVIEw(LayoutInflater inflater,@Nullable Bundle savedInstanceState) { mPrevIEwPlayVIDeoSubscriber.register(); VIEw vIEw = inflater.inflate(R.layout.fragment_prevIEw_vIDeo,null); mPhotoVIEw = vIEw.findVIEwByID(R.ID.photoVIEw); mTextureVIEw = vIEw.findVIEwByID(R.ID.surfaceVIEw); mUrl = getArguments().getString("url"); mposition = getArguments().getInt("position"); layoutPlayer(); loadVIDeoScreenshot(getContext(),mUrl,mPhotoVIEw,1); vIEw.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw vIEw) { release(); getActivity().finish(); } }); initTextureMedia(); return vIEw; } private voID initTextureMedia() { mTextureVIEw.setSurfaceTextureListener(mSurfaceTextureListener); } private voID play(String url) { try { mIjkVodMediaPlayer = new AndroIDMediaPlayer(); mIjkVodMediaPlayer.reset(); mIjkVodMediaPlayer.setDataSource(url); //让MediaPlayer和TextureVIEw进行视频画面的结合 mIjkVodMediaPlayer.setSurface(mSurface); //设置监听 mIjkVodMediaPlayer.setonBufferingUpdateListener((mp,percent) -> { }); mIjkVodMediaPlayer.setonCompletionListener(mp -> { mp.seekTo(0); mp.start(); }); mIjkVodMediaPlayer.setonInfoListener((mp1,what,extra) -> { if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) { mPhotoVIEw.setVisibility(VIEw.GONE); mIsFirstPrepared = true; } return false; }); mIjkVodMediaPlayer.setonErrorListener((mp,extra) -> false); mIjkVodMediaPlayer.setonPreparedListener(mp -> { mp.start(); if (!mIsFirstPrepared){ }else { mPhotoVIEw.setVisibility(VIEw.GONE); } }); mIjkVodMediaPlayer.setScreenOnWhilePlaying(true);//在视频播放的时候保持屏幕的高亮 if (mIsSelected){ //异步准备 mIjkVodMediaPlayer.prepareAsync(); } } catch (Exception e) { e.printstacktrace(); } } private Surface mSurface; private TextureVIEw.SurfaceTextureListener mSurfaceTextureListener = new TextureVIEw.SurfaceTextureListener() { @OverrIDe public voID onSurfaceTextureAvailable(SurfaceTexture surface,int wIDth,int height) { mSurface = new Surface(surface); play(mUrl); } @OverrIDe public voID onSurfaceTextureSizeChanged(SurfaceTexture surface,int height) { } @OverrIDe public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { if (mSurface != null){ mSurface.release(); mSurface = null; } if (mTextureVIEw != null){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mTextureVIEw.releasePointerCapture(); } } release(); return false; } @OverrIDe public voID onSurfaceTextureUpdated(SurfaceTexture surface) { } }; @OverrIDe public voID onStart() { super.onStart(); } @OverrIDe public voID onAttach(Context context) { super.onAttach(context); } @OverrIDe public voID onDetach() { super.onDetach(); } @OverrIDe public voID onPause() { MDLog.e("liuxu","onPause" + mposition); //处理锁屏时播放器停止播放 if (mIjkVodMediaPlayer != null && mIjkVodMediaPlayer.isPlaying()){ mIjkVodMediaPlayer.pause(); mIjkVodMediaPlayer.stop(); } super.onPause(); } //屏幕打开时重新播放 @OverrIDe public voID onResume() { MDLog.e("liuxu","onResume" + mposition); super.onResume(); if (mIsSelected && mIjkVodMediaPlayer != null && !mIjkVodMediaPlayer.isPlaying()) { mIjkVodMediaPlayer.prepareAsync(); } } @OverrIDe public voID onDestroy() { MDLog.e("liuxu","onDestroy"); release(); if (mPrevIEwPlayVIDeoSubscriber.isRegister()) { mPrevIEwPlayVIDeoSubscriber.unregister(); } super.onDestroy(); } private voID release() { if (mIjkVodMediaPlayer == null) { return; } if (mIjkVodMediaPlayer.isPlaying()) { mIjkVodMediaPlayer.stop(); } mIjkVodMediaPlayer.release(); mIjkVodMediaPlayer = null; } @OverrIDe public boolean getUserVisibleHint() { return super.getUserVisibleHint(); } /** * 动态设置视频宽高信息 */ private voID layoutPlayer() { //获取视频宽高比 getPlayInfo(mUrl); float ratio = float.parsefloat(mHeight) / float.parsefloat(mWIDth); MDLog.e("type",mposition + "ratio" + ratio); int type = 0; //添加容错值 if (ratio < MediaConstants.INSTANCE.getASPECT_RATIO_1_1().tofloat() + MediaConstants.INSTANCE.getSCREEN_DEFAulT_VALUE() && ratio > MediaConstants.INSTANCE.getASPECT_RATIO_1_1().tofloat() - MediaConstants.INSTANCE.getSCREEN_DEFAulT_VALUE()) { type = ScreenAdapterUtils.INSTANCE.getSCALE_TYPE_11(); } else if (ratio < MediaConstants.INSTANCE.getASPECT_RATIO_4_3().tofloat() + MediaConstants.INSTANCE.getSCREEN_DEFAulT_VALUE() && ratio > MediaConstants.INSTANCE.getASPECT_RATIO_4_3().tofloat() - MediaConstants.INSTANCE.getSCREEN_DEFAulT_VALUE()) { type = ScreenAdapterUtils.INSTANCE.getSCALE_TYPE_43(); MDLog.e("type","43"); } else if (ratio < MediaConstants.INSTANCE.getASPECT_RATIO_16_9().tofloat() + MediaConstants.INSTANCE.getSCREEN_DEFAulT_VALUE() && ratio > MediaConstants.INSTANCE.getASPECT_RATIO_16_9().tofloat() - MediaConstants.INSTANCE.getSCREEN_DEFAulT_VALUE()) { type = ScreenAdapterUtils.INSTANCE.getSCALE_TYPE_169(); MDLog.e("type","169"); } FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mTextureVIEw.getLayoutParams(); layoutParams.height = ScreenAdapterUtils.INSTANCE.getSurfaceHeight(type); mTextureVIEw.setLayoutParams(layoutParams); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mPhotoVIEw.getLayoutParams(); params.height = ScreenAdapterUtils.INSTANCE.getSurfaceHeight(type); mPhotoVIEw.setLayoutParams(params); MDLog.e("params.height",params.height + ""); } private voID getPlayInfo(String mUri) { androID.media.MediaMetadataRetrIEver mmr = new androID.media.MediaMetadataRetrIEver(); try { if (mUri != null) { mmr.setDataSource(mUri); } else { //mmr.setDataSource(mFD,mOffset,mLength); } //宽 mWIDth = mmr.extractMetadata(androID.media.MediaMetadataRetrIEver.MetaDATA_KEY_VIDEO_WIDTH); //高 mHeight = mmr.extractMetadata(androID.media.MediaMetadataRetrIEver.MetaDATA_KEY_VIDEO_HEIGHT);// mBitmap = mmr.getFrameatTime(1 ); } catch (Exception ex) { } finally { mmr.release(); } } public static voID loadVIDeoScreenshot(final Context context,String uri,ImageVIEw imageVIEw,long frameTimeMicros) { // 这里的时间是以微秒为单位 Requestoptions requestoptions = Requestoptions.frameOf(frameTimeMicros); requestoptions.set(FRAME_OPTION,MediaMetadataRetrIEver.OPTION_CLOSEST); requestoptions.transform(new Bitmaptransformation() { @OverrIDe protected Bitmap transform(@NonNull BitmapPool pool,@NonNull Bitmap totransform,int outWIDth,int outHeight) { return totransform; } @OverrIDe public voID updatediskCacheKey(MessageDigest messageDigest) { try { messageDigest.update((context.getPackagename() + "Rotatetransform").getBytes("utf-8")); } catch (Exception e) { e.printstacktrace(); } } }); GlIDe.with(context).load(uri).apply(requestoptions).into(imageVIEw); }}@H_404_78@
4.结语
笔者使用这种方式实现了项目需求,但是由于本人接触音视频的相关内容比较少,全是在不断探索和学习中前进,如有不足之处请评论指正,谢谢。大家共同学习共同进步。
好了以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程小技巧的支持。
您可能感兴趣的文章:Android使用ViewPager加载图片和轮播视频Android开发之使用ViewPager实现图片左右滑动切换效果android 解决ViewPager加载大量图片内存溢出问题Android ViewPager实现图片轮播效果Android 利用ViewPager实现图片可以左右循环滑动效果附代码下载使用ViewPager实现左右循环滑动及滑动跳转仿网易新闻客户端头条ViewPager嵌套实例Android利用ViewPager实现滑动广告板实例源码Android App中ViewPager所带来的滑动冲突问题解决方法@H_404_78@@H_404_78@ 总结以上是内存溢出为你收集整理的Android ViewPager中显示图片与播放视频的填坑记录全部内容,希望文章能够帮你解决Android ViewPager中显示图片与播放视频的填坑记录所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)