2013-02-14 123 views
0

我試圖將父容器寬度設置爲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寬高比。

回答

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是視頻的當前尺寸。 希望有所幫助。 :)

+3

我沒有真正擁有視頻的當前尺寸,因爲播放器是在創建選項卡時創建的,然後用戶單擊列表項目播放視頻。視頻可以是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