在VideoView中放置video

所以我扩展了VideoView的onMeasure以扩大video,以适应全屏视图。

这里是如何:

public void setVideoAspect(int w,int h){ wVideo=w; hVideo=h; onMeasure(w, h); } @Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if(wVideo!=0 && hVideo!=0) setMeasuredDimension(wVideo,hVideo); } 

我用屏幕的显示度量(宽度,高度)调用setVideoAspect()。 问题是,这种方法拉伸video适合在屏幕内。 我希望能够保持宽高比。 (我有4:3的video和3:2的屏幕尺寸。)我使用下面的代码给保留的比例测量视图:

 int height = (int) (metrics.widthPixels*3/(float)4); int width= metrics.widthPixels; mVideoView.setVideoAspect(width,height); 

所以这样做的工作,但有一个问题:它给了我一个4:3的video与屏幕的宽度,并正确地缩放高度,但它不居中的video。 (它只是裁剪video的底部而不是顶部和底部)。我有一个包含VideoView的相对布局,以VideoView的重心为中心。

尝试使用FrameLayout。 我不知道为什么,但如果我在我的代码中使用线性或相对它不会居中,但帧。 这里是适合我的video到屏幕的XML,保持比例和居中:

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/bg"> <!-- Video player --> <VideoView android:id="@+id/surface_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center"> </VideoView> </FrameLayout> 

卡梅隆的答案以编程的方式(如果像我这样的人需要它)这个代码是在我的代码中的一个活动的onCreate(下面的“this”指的是活动)

  FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); FrameLayout fl = new FrameLayout(this); fl.setLayoutParams(lp); VideoView vv = new VideoView(this); FrameLayout.LayoutParams lp2 = new FrameLayout.LayoutParams(lp); lp2.gravity = Gravity.CENTER; vv.setLayoutParams(lp2); fl.addView(vv); setContentView(fl); 

为了将video集中在RelativeLayout中,我添加了layout_gravity="center" ad layout_centerInParent="true" 。 它适用于我的Android 4.3手机。

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <VideoView android:id="@+id/surface_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_centerInParent="true" /> </RelativeLayout>