0

我扩展了 RelativeLayout 类,并按照我认为需要的方式实现了所有构造函数。我还在 xml 布局中添加了一个子元素,就像使用常规的 RelativeLayout 一样。现在,问题是,我似乎无法访问自定义布局中的孩子!奇怪的是,我可以(在图形布局中)选择子视图,并且自定义布局被描述为“父”,但是当尝试以相反的方式进行时没有骰子。

我如何“告诉”班级它实际上有孩子?代码如下!

谢谢!

private void init(Context context) {
    System.out.println(this.getChildCount()); // Always returns 0
}

public CustRLayout(Context context) {
    super(context);
    init(context);
}

public CustRLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public CustRLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context);
}

和 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <app.hobi.CustRLayout android:id="@+id/cust"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
        <ImageView 
            android:id="@+id/childView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/img"
            android:src="@drawable/an_image" />
    </app.hobi.CustRLayout>

    <app.hobi.SomeOtherView android:id="@+id/other"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</RelativeLayout>
4

1 回答 1

2

稍后(在调用构造函数之后)通过addChild(). 因此,在后期状态下查询 childCount,例如:在 onMeasure() 或使用ViewTreeObserver

于 2012-04-23T13:02:27.827 回答