2013-07-25 54 views
4

我有一個正在擴展LinearLayout的自定義視圖。這個自定義視圖包含幾個其他視圖,它們應該完全像LinearLayout一樣佈局,但是,我沒有設法正確地佈置它們......所有子視圖相互疊加,隱藏了之前添加的所有子視圖。擴展LinearLayout自定義佈局的Onlayout方法

我onLayout和onMeasure如下:

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    // Do nothing. Do not call the superclass method--that would start a layout pass 
    // on this view's children. PieChart lays out its children in onSizeChanged(). 
    super.onLayout(changed, l, t, r, b); 
    Log.e(LOG_TAG, LOG_TAG + ".onLayout: " + l + ", " + t + ", " + r + ", " + b); 

    int iChildCount = this.getChildCount(); 
    for (int i = 0; i < iChildCount; i++) { 
     View pChild = this.getChildAt(i); 
     pChild.layout(l, t, pChild.getMeasuredWidth(), pChild.getMeasuredHeight()); 
    } 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    // Try for a width based on our minimum 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: width: " + widthMeasureSpec + " getWidth: " + MeasureSpec.getSize(widthMeasureSpec)); 
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: height: " + heightMeasureSpec + " getHeight: " + MeasureSpec.getSize(heightMeasureSpec)); 
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: getPaddingLeft: " + getPaddingLeft() + " getPaddingRight: " + getPaddingRight()); 
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: getPaddingTop: " + getPaddingTop() + " getPaddingBottom: " + getPaddingBottom()); 

    // http://stackoverflow.com/a/17545273/474330 
    int iParentWidth = MeasureSpec.getSize(widthMeasureSpec); 
    int iParentHeight = MeasureSpec.getSize(heightMeasureSpec); 

    this.setMeasuredDimension(iParentWidth, iParentHeight); 

    int iChildCount = this.getChildCount(); 
    for (int i = 0; i < iChildCount; i++) { 
     View pChild = this.getChildAt(i); 
     this.measureChild(pChild, 
       MeasureSpec.makeMeasureSpec(iParentWidth, MeasureSpec.EXACTLY), 
       MeasureSpec.makeMeasureSpec(iParentHeight, MeasureSpec.EXACTLY) 
     ); 
    } 
} 

如何設置x位置,y位置,寬度和高度,是我自定義視圖的? 我已將我的自定義視圖的LayoutParam設置爲WRAP_CONTENT,但它仍然像FILL_PARENT一樣佔據了父級中可用的所有可用空間。似乎我所有的努力來改變位置或大小根本不工作(我甚至嘗試setPadding試圖控制位置)

回答

1

我一直在努力解決這個問題。它看起來很長時間以來一直被問到,但這是我做了什麼來實現它的工作。也許它會幫助某個人。

擴展LinearLayout意味着如果您希望它顯示您的子視圖與LinearLayout相同,則不必重寫onLayout。我所需要做的就是按照預期的方式進行佈局,即刪除我的onLayout方法,讓LinearLayout類負責處理這個問題。

0

layout()方法的第三個和第四個參數分別是「正確的位置,相對於父母」和「相對於父母的底部位置」,而不是您認爲它們的寬度和高度。