Is there a way to have a media file (audio/video
) running in a cardview
layout? I want to have a video
preview of the file inside a card layout
, when the user clicks on the card the video/audio
is taken fullscreen and played, just like Facebook's feed.
问题:
回答1:
In order to get that kind of functionality you have to solve a few problems:
You cannot use
VideoView
in a list because it is extendingSurfaceView
, and if playback is on and user starts scrolling, the visual effect will look like video is trying to catch the scroll. So you need a specialVideoView
that is based on something else, for exampleTextureView
.Managing video player state: in order to start/stop playback we need to call a few methods of
MediaPlayer.class
:setDataSource() prepare() start() stop() reset() release()
These methods are direct calls to hardware and it may take some time before hardware will respond. So we cannot call it in UI thread. It will block it for more than 16 milliseconds, so user will see a lagging scrolled list. We have to call it from a background thread.
You need to track in run time which view on the screen is active and this view should be playing.
I've created an opensource project called VideoPlayerManager.
It is thoroughly documented and some basic flows are handled in the demo application. It is not ready for production but if you need some reference of how to get this kind of functionality, you can find it there.
P.S. Regarding CardView: it is a regular view. You can put a video player into it and get video playback in CardView.