First, create a relative layout using Gravity.CENTER and attach your surface view to it. This will center the video inside the screen.
Also, if you are using an activity, use a black theme to avoid the gradient
In your SurfaceView, create a listener:
mMediaPlayer = new MediaPlayer();
...
MediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener = new MediaPlayer.OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { setFitToFillAspectRatio(mp, width, height); } }; mMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
...
Finally, the fill method in your SurfaceView. It will work on landscape and portrait
private void setFitToFillAspectRatio(MediaPlayer mp, int videoWidth, int videoHeight) { if(mp != null) { Integer screenWidth = ((Activity) mContext).getWindowManager().getDefaultDisplay().getWidth(); Integer screenHeight = ((Activity) mContext).getWindowManager().getDefaultDisplay().getHeight(); android.view.ViewGroup.LayoutParams videoParams = getLayoutParams(); if (videoWidth > videoHeight) { videoParams.width = screenWidth; videoParams.height = screenWidth * videoHeight / videoWidth; } else { videoParams.width = screenHeight * videoWidth / videoHeight; videoParams.height = screenHeight; } setLayoutParams(videoParams); } }
source share