2010-04-27 60 views
0

我有一個Activity,它將顯示由2部分組成的自定義視圖。我希望一部分是可見屏幕高度的1/3,另一部分是2/3。如何正確調整包含視圖的大小

我可以覆蓋onMeasure()並使用顯示度量來查找顯示器的高度,但這並不考慮電池條或視圖標題大小。

DisplayMetrics dm = new DisplayMetrics(); 
((WindowManager)contxt.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm); 
int height = dm.heightPixels; 

如何判斷可顯示區域的高度?我準備重寫layout或其他什麼。什麼是Android的最佳實踐?我已經看到了這條線上的其他問題,但他們沒有定論。

回答

1

我想出了一個辦法。我重寫了RelativeLayout,並讓它保持指向我的上部和下部視圖的指針。然後,當它處理onMeasure時,它會在我的2個視圖中設置所需的高度。他們在處理onMeasure時使用所需的高度。這給了我一個2/3可見區域的視圖,另一個在下面。

- 從我的佈局類

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    // set default screen heights 
    int heightSize = MeasureSpec.getSize(heightMeasureSpec); 
    if (upper != null) 
     upper.setPrefHeight((heightSize*2)/3); 
    if (lower != null) 
     lower.setPrefHeight(heightSize/3); 

    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

} 

- 從View派生類

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    setMeasuredDimension(measureWidth(widthMeasureSpec), 
      measureHeight(heightMeasureSpec)); 
} 

/** 
* Determines the width of this view 
* @param measureSpec A measureSpec packed into an int 
* @return The width of the view, honoring constraints from measureSpec 
*/ 
private int measureWidth(int measureSpec) { 
    int result = 0; 
    int specMode = MeasureSpec.getMode(measureSpec); 
    int specSize = MeasureSpec.getSize(measureSpec); 

    if (specMode == MeasureSpec.EXACTLY) { 
     // We were told how big to be 
     result = specSize; 
    } else { 
     DisplayMetrics dm = new DisplayMetrics(); 
     ((WindowManager)contxt.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm); 
     result = dm.widthPixels; 
    } 
    width = result; 
    return result; 
} 

/** 
* Determines the height of this view 
* @param measureSpec A measureSpec packed into an int 
* @return The height of the view, honoring constraints from measureSpec 
*/ 
private int measureHeight(int measureSpec) { 
    int result = 0; 
    int specMode = MeasureSpec.getMode(measureSpec); 
    int specSize = MeasureSpec.getSize(measureSpec); 

    if (specMode == MeasureSpec.EXACTLY) { 
     // We were told how big to be 
     result = specSize; 
    } else { 
     result = prefHeight; 
    } 
    height = result; 

    return result; 
} 
相關問題