2011-06-03 73 views

回答

4

這不是在已知的onCreate()。你應該做的是正確地參與視圖層次結構佈局過程。你不要在onCreate()中做你的佈局,你可以在佈局管理器的視圖層次結構中進行佈局。如果你有一些你不能用標準佈局管理器來實現的特殊佈局,那麼編寫你自己的佈局非常容易 - 只需實現一個ViewGroup子類,它在onMeasure()和onLayout()中做適當的事情。

這是唯一正確的方法,因爲如果可用顯示大小發生變化,您的onCreate()將不會再次運行,但視圖層次結構將通過其佈局過程來確定放置其視圖的正確新位置。屏幕尺寸可能會隨着你的變化而變化的原因是多種多樣的 - 例如,在Xoom平板電腦上插入HDMI輸出時,它使系統條更大,以便當它將顯示器映射到720p屏幕底部的應用程序不會被切斷。

例如,下面是實現的FrameLayout一個簡單版本的佈局管理器:

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    final int childCount = getChildCount(); 
    for (int i = 0; i < childCount; i++) { 
     final View child = getChildAt(i); 

     int childRight = getPaddingLeft() 
       + child.getMeasuredWidth() - getPaddingRight(); 
     int childBottom = getPaddingTop() 
       + child.getMeasuredHeight() - getPaddingBottom(); 
     child.layout(getPaddingLeft(), getPaddingTop(), childRight, childBottom); 
    } 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    final int count = getChildCount(); 

    int maxHeight = 0; 
    int maxWidth = 0; 
    int measuredChildState = 0; 

    // Find rightmost and bottom-most child 
    for (int i = 0; i < count; i++) { 
     final View child = getChildAt(i); 
     if (child.getVisibility() != GONE) { 
      measureChild(child, widthMeasureSpec, heightMeasureSpec); 
      maxWidth = Math.max(maxWidth, child.getMeasuredWidth()); 
      maxHeight = Math.max(maxHeight, child.getMeasuredHeight()); 
      measuredChildState = combineMeasuredStates(measuredChildState, 
        child.getMeasuredState()); 
     } 
    } 

    // Account for padding too 
    maxWidth += getPaddingLeft() + getPaddingRight(); 
    maxHeight += getPaddingTop + mPaddingBottom(); 

    // Check against our minimum height and width 
    maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); 
    maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); 

    setMeasuredDimension(resolveSizeAndState(maxWidth, 
        widthMeasureSpec, measuredChildState), 
      resolveSizeAndState(maxHeight, heightMeasureSpec, 
        measuredChildState<<MEASURED_HEIGHT_STATE_SHIFT)); 
} 

注意最後一行有實施測量開始API 11的最好方式,因爲它可以讓你傳播狀態比如「佈局不合適」,可用於確定對話框所需的大小。您可能不需要擔心這樣的事情,在這種情況下,您可以將其簡化爲,關於平臺的所有版本的作品形式:

setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), 
      resolveSize(maxHeight, heightMeasureSpec)); 

還有一個稍微更復雜佈局的API演示:

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/animation/FixedGridLayout.html

0