基于父宽度的动态VideoView高度

时间:2013-02-14 03:21:55

标签: android android-layout android-widget

我尝试将VideoView调整为父容器宽度,然后设置高度以保持4:3的宽高比。我已经看到一些建议扩展VideoView课程并覆盖onMeasure的答案,但我不了解我获得的参数或如何使用它们:< / p>

package com.example;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.VideoView;

public class MyVideoView extends VideoView {

    public MyVideoView(Context context) {
        super(context);
    }

    public MyVideoView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyVideoView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
        Log.i("MyVideoView", "width="+widthMeasureSpec);
        Log.i("MyVideoView", "height="+heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

结果(在Nexus 7平板电脑上):

02-13 21:33:42.515: I/MyVideoView(12667): width=1073742463
02-13 21:33:42.515: I/MyVideoView(12667): height=1073742303

我试图实现以下布局:

平板电脑(肖像):

  • VideoView宽度 - 全屏或接近全屏。
  • VideoView height - 给定宽度
  • 保持4:3的宽高比
  • ListView - 显示在VideoView下方,以选择要播放的视频。

平板电脑(风景):

  • ListView - 显示在屏幕左侧,用于选择要播放的视频。
  • VideoView - 显示在屏幕右侧,应填充剩余宽度和设置高度,以保持4:3的宽高比。

1 个答案:

答案 0 :(得分:1)

试试这个:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
    int height = getDefaultSize(mVideoHeight, heightMeasureSpec);

            /**Adjust according to your desired ratio*/
    if (mVideoWidth > 0 && mVideoHeight > 0) {
        if (mVideoWidth * height > width * mVideoHeight) {
            // Log.i("@@@", "image too tall, correcting");
            height = (width * mVideoHeight / mVideoWidth);
        } else if (mVideoWidth * height < width * mVideoHeight) {
            // Log.i("@@@", "image too wide, correcting");
            width = (height * mVideoWidth / mVideoHeight);
        } else {
            // Log.i("@@@", "aspect ratio is correct: " +
            // width+"/"+height+"="+
            // mVideoWidth+"/"+mVideoHeight);
        }
    }

    setMeasuredDimension(width, height);

}

其中mVideoWidth和mVideoHeight是视频的当前维度。 希望有所帮助。 :)