在Android上播放視頻最簡單的方法是使用SDK中內置的VideoView,而後加上MediaController來控制視頻播放暫停等,可是這樣有一個缺點是沒法定製本身的控制UI,因此這裏提供一個自定義播放控件,它能夠設置多種自定義屬性(如loading樣式,錯誤視頻等),而且很容易在全屏與非全屏之間切換,另外支持Android V2.3及以上系統. java
項目地址: https://github.com/linsea/UniversalVideoView android
完整的使用方法請參考項目裏的Sample. git
1. 在build.gradle文件上加入如下依賴包. github
dependencies { compile 'com.linsea:universalvideoview:1.1.0@aar' }
<FrameLayout android:id="@+id/video_layout" android:layout_width="fill_parent" android:layout_height="200dp" android:background="@android:color/black"> <com.universalvideoview.UniversalVideoView android:id="@+id/videoView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" app:uvv_autoRotation="true" app:uvv_fitXY="false" /> <com.universalvideoview.UniversalMediaController android:id="@+id/media_controller" android:layout_width="fill_parent" android:layout_height="fill_parent" app:uvv_scalable="true" /> </FrameLayout>
3. 在onCreate方法中設置相關事件的監聽. app
View mBottomLayout; View mVideoLayout; UniversalVideoView mVideoView; UniversalMediaController mMediaController; mVideoView = (UniversalVideoView) findViewById(R.id.videoView); mMediaController = (UniversalMediaController) findViewById(R.id.media_controller); mVideoView.setMediaController(mMediaController); mVideoView.setVideoViewCallback(new UniversalVideoView.VideoViewCallback() { @Override public void onScaleChange(boolean isFullscreen) { this.isFullscreen = isFullscreen; if (isFullscreen) { ViewGroup.LayoutParams layoutParams = mVideoLayout.getLayoutParams(); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; mVideoLayout.setLayoutParams(layoutParams); //設置全屏時,無關的View消失,以便爲視頻控件和控制器控件留出最大化的位置 mBottomLayout.setVisibility(View.GONE); } else { ViewGroup.LayoutParams layoutParams = mVideoLayout.getLayoutParams(); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; layoutParams.height = this.cachedHeight; mVideoLayout.setLayoutParams(layoutParams); mBottomLayout.setVisibility(View.VISIBLE); } } @Override public void onPause(MediaPlayer mediaPlayer) { // 視頻暫停 Log.d(TAG, "onPause UniversalVideoView callback"); } @Override public void onStart(MediaPlayer mediaPlayer) { // 視頻開始播放或恢復播放 Log.d(TAG, "onStart UniversalVideoView callback"); } @Override public void onBufferingStart(MediaPlayer mediaPlayer) {// 視頻開始緩衝 Log.d(TAG, "onBufferingStart UniversalVideoView callback"); } @Override public void onBufferingEnd(MediaPlayer mediaPlayer) {// 視頻結束緩衝 Log.d(TAG, "onBufferingEnd UniversalVideoView callback"); } });
android:configChanges="orientation|keyboardHidden|screenSize
爲了保證定製UI的靈活度,提供如下屬性: ide
uvv_fitXY 佈局
UniversalVideoView的屬性,布爾值,true時設置視頻縮放時在X,Y方向上鋪滿View設置的寬度和高度,這樣可能使視頻變形.false時則縮放時保持視頻的長寬比例,與SDK中的VideoView相似. gradle
uvv_autoRotation ui
UniversalVideoView的屬性,布爾值,true時視頻會根據重力響應通知客戶進行全屏與非全屏之間的切換. this
uvv_scalable
UniversalMediaController屬性,布爾值,是否顯示控制條右下方的縮放按鈕,若是不想全屏播放時,能夠設置爲false不顯示.