Android从FrameLayout获取子对象
如果我创建两个类,一个扩展Android从FrameLayout获取子对象,android,android-layout,android-view,Android,Android Layout,Android View,如果我创建两个类,一个扩展FrameLayout的父类和一个扩展View的子类,然后使用XML对它们进行初始化。是否可以从父类构造函数获取子元素?如果我使用getChildAt(),我总是得到null,因为活动仍然没有创建 <com.example.Parent android:layout_width="match_parent" android:layout_height="200dp" android:layout_centerIn
FrameLayout
的父类和一个扩展View
的子类,然后使用XML
对它们进行初始化。是否可以从父类构造函数获取子元素?如果我使用getChildAt()
,我总是得到null,因为活动仍然没有创建
<com.example.Parent
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerInParent="true">
<com.example.Child
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.example.Child
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.Parent>
由于在构建
FrameLayout
时调用getChildAt
,因此得到的是空值(您的孩子仍然没有完全连接到视图)。一种解决方案是覆盖onLayout()
或onMeasure()
以获取您的孩子。在充气之前,您无法从父视图获取孩子视图
但您可以动态地执行此操作,但工作方式也相同,例如,您必须手动将视图添加到父视图中
然后可以从父视图中获取子视图 您无法在构造函数中获取子级
视图
尚未绘制。获取子视图的用例是什么?根据需要编辑您的问题,以便有人能够提供帮助。您可以查看onFinishInflate
函数。onFinishInflate()将完成此工作
public class Parent extends FrameLayout {
public Parent(@NonNull Context context) {
super(context);
this.getChildAt(0); // return null
}
...
}
public class Child extends View {
...
}