Search code examples
androidorientationandroid-videoview

Android: Video stretches on orientation change


I'm showing a video in a videoview:

In my XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:gravity="center"
  android:layout_height="fill_parent">

    <VideoView
    android:layout_gravity="center"
    android:id="@+id/videoview_player"
    android:layout_width="wrap_content"
     android:layout_height="wrap_content" />

</LinearLayout>

It looked like this works perfect. The video resizes itself so the screen is filled, while the video remains it's aspect ratio.

But on tablets, after like 30 - 60 seconds in portrait orientation, the video stretches to full screen. (It doesn't maintain the aspect ratio, it stretches the height)

Like this:

enter image description here


Solution

  • I ended up subclassing the VideoView:

    public class PlayerVideoView extends VideoView{
    
        private int mForceHeight = 0;
        private int mForceWidth = 0;
        public PlayerVideoView(Context context) {
            super(context);
        }
    
        public PlayerVideoView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public PlayerVideoView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public void setDimensions(int w, int h) {
            this.mForceHeight = h;
            this.mForceWidth = w;
    
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            setMeasuredDimension(mForceWidth, mForceHeight);
        }
    }
    

    Where in the onCreate i set the dimensions

    videoView.setDimensions(800, 600);
    

    Then in the

    @Override
    public void onConfigurationChanged(Configuration newConfig) {..}
    

    I manually set the dimensions for portrait or landscape, depending on the users device orientation.