问题
I was writing a custom ViewGroup
and came across the following problem:
The ViewGroup
should be usable by specifying properties in XML only.
However, I want to do some internal initialization in code after the ViewGroup
has been created and all its child View
s from XML have been added (that is, when the layout inflator has added all the child View
s of a ViewGroup
specified in XML).
All I found related to this are recommendations to use getViewTreeObserver().addOnGlobalLayoutListener(...)
.
However, this is called at least after each child View
is added and also after resuming an app etc. So it does not even make it possible to detect the moment when all child View
s have been added.
Is there a method called after all child View
s have been added to a ViewGroup
?
Related: When are child views added to Layout/ViewGroup from XML
回答1:
There is a callback: View.onFinishInflate()
.
From the documentation (which also has a section "Implementing a Custom View" describing all the callbacks):
Finalize inflating a view from XML. This is called as the last phase of inflation, after all child views have been added.
Simply override the method in your custom ViewGroup
:
public class MyViewGroup extends ViewGroup {
@Override
protected void onFinishInflate() {
super.onFinishInflate();
doMyInitialization();
}
}
来源:https://stackoverflow.com/questions/40183648/callback-after-all-child-views-from-xml-have-been-added-to-viewgroup