Been playing with ExoPlayer in Android and trying to resize a view to fit the aspect ratio of the video being played, i.e. fill the view with the video.
References:
- Change resize mode for ExoPlayer
- Change aspect ratio of SurfaceView for ExoPlayer video
- 5-part series on building video player using ExoPlayer
import android.view.ViewGroup.LayoutParams;
import com.google.android.exoplayer2.Player.EventListener;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.video.VideoListener;
public class MyView extends PlayerView {
public void someMethod() {
// code to create myPlayer of type SimpleExoPlayer...
// Listen to player events
myPlayer.addListener(new EventListener() {
// ...
});
// Listen to video events
myPlayer.addVideoListener(new VideoListener() {
// This is where we will resize view to fit aspect ratio of video
@Override
public void onVideoSizeChanged(
int width,
int height,
int unappliedRotationDegrees,
float pixelWidthHeightRatio
) {
// Get layout params of view
// Use MyView.this to refer to the current MyView instance
// inside a callback
LayoutParams p = MyView.this.getLayoutParams();
int currWidth = MyView.this.getWidth();
// Set new width/height of view
// height or width must be cast to float as int/int will give 0
// and distort view, e.g. 9/16 = 0 but 9.0/16 = 0.5625.
// p.height is int hence the final cast to int.
p.width = currWidth;
p.height = (int) ((float) height / width * currWidth);
// Redraw myView
MyView.this.requestLayout();
}
@Override
public void onRenderedFirstFrame() {
// ...
}
});
// some other code...
}
}

