2015-08-26 53 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。 –