基于父宽度的动态视频视图高度
问题描述:
我试图将父容器宽度设置为VideoView
,然后将高度设置为保持4:3宽高比。我见过的建议延长VideoView
类和压倒一切的onMeasure
一些答案,但我不明白,我得到或如何使用它们的参数:基于父宽度的动态视频视图高度
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高度 - 保持宽高比为4:3的宽高比
- ListView - 显示在VideoView下方以选择要播放的视频。
平板电脑(横向):
- 的ListView - 显示在屏幕的左侧,用于选择要播放的影片。
- VideoView - 出现在屏幕的右侧,应该填充剩余宽度和设置高度以保持4:3宽高比。
答
试试这个:
@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是视频的当前尺寸。 希望有所帮助。 :)
我没有真正拥有视频的当前尺寸,因为播放器是在创建选项卡时创建的,然后用户单击列表项目播放视频。视频可以是640x480或320x240。这似乎工作正常:'int width = getDefaultSize(0,widthMeasureSpec); int height = getDefaultSize(0,heightMeasureSpec); \t setMeasuredDimension(width,width/4 * 3);' – DanielB6 2013-02-14 14:30:56