2015-08-26 54 views
0

我有一個從視圖組類延伸的類。現在我知道在onLayout中你必須調用每個孩子的佈局方法。這裏的問題是應該將什麼值傳遞給子佈局。如何正確覆蓋Viewgroup類中的onLayout方法

在我看來,我膨脹一個XML並將其附加到這個類(寬度和高度定義在XML中)。在onlayout中,我得到一個正確的孩子數,但是孩子的寬度和高度都是0。我如何獲得孩子的寬度和高度。

如果我在設置位置和度量,那麼對策方法是什麼?我以爲我們想要測量那裏的孩子。

以下是一些參考源代碼。

public BaseWidget(Context context, int resourceId) { 
    super(context); 
    initWithResourceID(resourceId); 
} 

private void initWithResourceID(int resourceId) { 
    inflate(getContext(), resourceId, this); 
} 

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    final int count = getChildCount(); 
    for (int i = 0; i < count; i++) { 
     View child = getChildAt(i); 
     getChildAt(i).layout(l, t, r, b); 
//  getChildAt(i).layout((int)child.getX(), (int)(child.getY() + child.getMeasuredHeight()), (int) (child.getX() + child.getMeasuredWidth()), (int)child.getY()); 
    } 
} 

的XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="150dp" 
android:layout_height="90dp" 
android:background="@color/ripple_material_light" 
android:orientation="vertical" 
android:padding="20dp"> 

<RelativeLayout 
    android:id="@+id/texts" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <TextView 
     android:id="@+id/title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:text="1" /> 

    <TextView 
     android:id="@+id/asideTitle" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:text="2" /> 
</RelativeLayout> 

<View 
    android:id="@+id/detailedView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 

</View> 
</LinearLayout> 

當我打電話getChildAt(i).layout(l, t, r, b);孩子繪製在整個父。

當我打電話

getChildAt(i).layout((int)child.getX(), (int)(child.getY() + 
child.getMeasuredHeight()), (int) (child.getX() + 
child.getMeasuredWidth()), (int)child.getY()); 

什麼也不繪製

所以基本上我想知道什麼,我們應該傳遞給孩子..和是什麼onmeasure和onlayout之間的主要區別。我希望我明確提出我的問題。

回答

1

您必須在嘗試獲取其高度和寬度之前先測量孩子。在onLayout中,你決定了孩子的位置。 測量完畢後,您將獲得所有兒童的身高和身高,然後在其幫助下,您可以定位兒童。您可以根據它的高度和寬度來設置它的左,右,上,下點。 例如,如果你想在位置(0,0)的孩子,然後在onLayout

child.layout(0,0,child.getMeasuredWidth(), child.getMeasuredHeight()); 

如果右側和底部點提到的錯誤的,認爲可以剪切/放大/縮小。

+0

謝謝你指點我在正確的方向。我沒有重寫onmeasure函數。還有一件事,我們是否需要爲從viewgroup擴展的每個類實現自己的佈局參數,還是我們也可以使用現有的佈局參數? –

+1

您可以使用ViewGroup本身的LayoutParams。 –