【问题标题】:How to correctly override onLayout Method in a Viewgroup class如何在 Viewgroup 类中正确覆盖 onLayout 方法
【发布时间】:2015-08-26 06:51:13
【问题描述】:

我有一个从视图组类扩展而来的类。现在我知道在 onLayout 中你必须调用每个孩子的布局方法。这里的问题是应该将哪些值传递给子布局。

在我看来,我膨胀了一个 xml 并将其附加到这个类(宽度和高度在 xml 中定义)。在 onlayout 中,我得到一个正确的孩子计数,但孩子的宽度和高度返回 0。我如何获得孩子的宽度和高度。

如果我要设置位置和测量值,那么 onmeasure 方法的用途是什么?我以为我们应该测量那里的孩子。

以下是一些源代码供参考。

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之间的主要区别是什么。我希望我把我的问题说清楚。

【问题讨论】:

    标签: android android-layout viewgroup


    【解决方案1】:

    您必须先测量孩子们的高度和宽度。在 onLayout 中,您决定孩子的位置。 测量后,您将获得所有孩子的高度和宽度,然后在它的帮助下,您可以定位孩子。您可以根据它的高度和宽度设置它的左、右、上、下点。 比如你想把child定位在(0,0),那么在onLayout中

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

    如果右点和下点提到错误,视图可能会被剪切/放大/缩小。

    【讨论】:

    • 感谢您为我指明了正确的方向。我没有覆盖 onmeasure 函数。还有一件事,我们是否需要为从视图组扩展的每个类实现自己的布局参数,还是也可以使用现有的?
    • 可以使用ViewGroup本身的LayoutParams。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多